一、if
#include <iostream> using namespace std; int main() { int num1 = 10; int num2 = 20; // 单行条件 if (num1 < num2) { cout << "num1 小于 num2" << endl; } // 多行条件 if (num1 > num2) { cout << "num1 大于 num2" << endl; } else { cout << "num1 小于 num2" << endl; } //多条件语句 int num3; cout << "请输入一个数字:" << endl; cin >> num3; if (num3 > 10) { cout << "num3 大于 10" << endl; } else if (num3 > 9) { cout << "num3 大于 9" << endl; } else if (num3 > 8) { cout << "num3 大于 8" << endl; } else if (num3 > 7) { cout << "num3 大于 7" << endl; } else { cout << "num3 小于等于 7" << endl; } // 嵌套if int num4 = 10; int num5 = 20; if (num4 == 10) { cout<<"num4 等于10"<<endl; if(num5==20){ cout<<"num4 等于10 num5 等于20"<<endl; }else{ cout<<"num4 等于10 num5 不等于20"<<endl; } } else { cout<<"num4 不等于10"<<endl; } return 0; }
num1 小于 num2 num1 小于 num2 请输入一个数字: 6 num3 小于等于 7 num4 等于10 num4 等于10 num5 等于20
二、三目
#include <iostream> using namespace std; int main() { int a = 10; int b = 20; // 三目运算返回值 int c = a > b ? a : b; cout << "c=" << c << "\n"; // 三目运算返回变量 (a > b ? a : b) = 1000; cout << a << endl; cout << b << endl; return 0; }
c=20 10 1000
三、switch
#include <iostream> using namespace std; int main() { //switch cout << "请输入你的成绩:" << endl; int score = 0; cin >> score; switch (score) { case 10: cout << "很优秀10" << endl; break; case 9: cout << "很优秀9" << endl; break; case 8: cout << "很优秀8" << endl; break; case 7: cout << "很优秀7" << endl; break; default: cout << "^_^" << endl; break; } return 0; }
请输入你的成绩: 9 很优秀9
switch的case中有多行代码时,使用{}。
#include <iostream> #include <string> using namespace std; int main() { int select = 2; switch (select) { case 1: cout << "1" << endl; break; case 2: { cout << "1" << endl; cout << "1" << endl; cout << "1" << endl; cout << "1" << endl; } break; default: break; } return 0; }