C++ 判断语句学习笔记
一、条件语句
1. if 语句
当程序需要根据某种条件来决定是否执行某段代码时,就可以使用 if
语句。
c++Copy Codeif (condition) {
// Code block to be executed if the condition is true
}
例如:
c++Copy Codeint x = 5;
if (x > 10) {
cout << "x is greater than 10" << endl;
} else {
cout << "x is less than or equal to 10" << endl;
}
2. switch 语句
当需要根据不同的值执行不同的代码块时,可以使用 switch
语句。在 switch
语句中,分别列出每个可能的值,并指定对应的代码块。
c++Copy Codeswitch (expression) {
case value1:
// Code block to be executed if expression == value1
break;
case value2:
// Code block to be executed if expression == value2
break;
default:
// Code block to be executed if expression does not match any of the values
break;
}
例如:
c++Copy Codechar grade = 'B';
switch (grade) {
case 'A':
cout << "Excellent!" << endl;
break;
case 'B':
cout << "Good job!" << endl;
break;
case 'C':
cout << "Well done" << endl;
break;
default:
cout << "Invalid grade" << endl;
break;
}
二、三目运算符
三目运算符也称为条件运算符。它是一个简短的 if-else 语句,可以用一行代码实现。
c++Copy Codecondition ? true_expression : false_expression;
例如:
c++Copy Codeint a = 10, b = 5;
int max_value = (a > b) ? a : b;
cout << "The maximum value is: " << max_value << endl;
以上就是 C++ 中判断语句的学习笔记。