【笔记】C++.04102020 C++17标准带有初始化器的if和switch语句

需要支持C++17标准。

if(initializer;variable)

switch(initializer;variable)

initiallizer-初始化器

 例子:

if用例:

#include<iostream>
#include<cstdlib>
using std::cout;
using std::cin;
using std::endl;

int main() {
    cout << "正在生成0~100之间的数" << endl << "请输入你猜测的整数:(你有1次机会)";
    auto x{ 0 };
    cin >> x;
    if (int z = rand() % 100; x > z) {
        cout << "你猜大了,正确的数是" << z << endl;
    }
    else if (x < z) {
        cout << "你猜小了,正确的数是" << z << endl;
    }
    else {
        cout << "你猜对了" << endl;
    }
    
}

switch用例:

#include<iostream>
using std::cout;
using std::cin;
using std::endl;

int main() {
    cout << "输入课程成绩:";
    int score{ 0 };
    cin >> score;
    cout << "成绩评级:" << endl;
    switch (int x = score / 10; x) {
    case 10:
    case 9:
        cout << "A" << endl;
        break;
    case 8:
        cout << "B" << endl;
        break;
    case 7:
        cout << "C" << endl;
        break;
    case 6:
    default:
        cout << "D" << endl;
    }

}
发布了18 篇原创文章 · 获赞 0 · 访问量 346

猜你喜欢

转载自blog.csdn.net/qq_43750882/article/details/105433428