C++中的if...elif条件语句
if...elif条件语句是C++中的一种流程控制语句,它能够检查一个或者多个条件,根据检查的结果执行不同的代码块。它的语法如下:
if (condition1) { // Execute this block if condition1 is true } else if (condition2) { // Execute this block if condition2 is true } else { // Execute this block if both condition1 and condition2 are false }
如果condition1为真,则执行第一个代码块;如果condition1为假,则检查condition2,如果condition2也为真,则执行第二个代码块;如果condition1和condition2都为假,则执行第三个代码块。
if...elif条件语句可以用来检查多个条件,也可以用在多个if语句之间,从而更加灵活地控制流程。例如,可以使用if...elif条件语句来检查用户输入的数字,根据不同的数字执行不同的动作:
int num; cin >> num; if (num == 1) { cout << "You entered 1" << endl; } else if (num == 2) { cout << "You entered 2" << endl; } else if (num == 3) { cout << "You entered 3" << endl; } else { cout << "You entered an invalid number" << endl; }
if...elif条件语句还可以用来检查某个范围内的值,例如,可以使用if...elif条件语句来检查用户输入的数字是否在1到10之间:
int num; cin >> num; if (num >= 1 && num <= 10) { cout << "The number is between 1 and 10" << endl; } else { cout << "The number is not between 1 and 10" << endl; }
if...elif条件语句还可以用来检查两个或者多个条件是否同时满足,例如,可以使用if...elif条件语句来检查用户输入的数字是否在1到10之间,并且是偶数:
int num; cin >> num; if (num >= 1 && num <= 10) { if (num % 2 == 0) { cout << "The number is between 1 and 10 and is even" << endl; } else { cout << "The number is between 1 and 10 but is not even" << endl; } } else { cout << "The number is not between 1 and 10" << endl; }
以上就是C++中if...elif条件语句的使用方法,它可以用来检查一个或者多个条件,从而更加灵活地控制流程。