具有多个变量的 if 语句

If statements with multiple variables

本文关键字:if 语句 变量      更新时间:2023-10-16

我正在尝试使用具有多个比较操作if语句,但day变量在我的if语句中不起作用。

这是我的代码:

int day;
string rain;
cout << "What day of the week is it?" << endl;
cin >> day;
while (0 < day < 8)
{
cout << "Is it raining? Please type 'yes' or 'no' " << endl;
cin >> rain;
if ((0 < day < 3) && (rain == "yes"))
cout << "Read in bed" << endl;
else if ((0 < day < 3) && (rain == "no"))
cout << "Go out and play!" << endl;
else if ((2 < day < 8) && (rain == "yes"))
cout << "Take an umbrella!" << endl;
else
cout << "No umberella needed" << endl;
cout << "What day of the week is it?" << endl;
cin >> day;
}
cout << "Invalid day sorry" << endl;

Read in bedgo out and play,但从不Take an umbrella

如果我把day = 9

.

您需要使用逻辑 AND (&&( 运算符更正涉及变量day条件。

例如,0 < day < 8意味着您正在针对两个不同的值测试day,即day是否在此范围内。因此,在您的情况下,应使用逻辑运算符和&&将这两个比较结合起来。因此,它应该是这样的:

day > 0 && day < 8

比较day的其他条件也是如此。


有关逻辑运算符的更多详细信息,请参阅参考: https://en.cppreference.com/w/cpp/language/operator_logical

使用7 < day && day < 0

一旦你写了0 < day < 3C++计算其中一个,然后比较变成布尔<整数>

我觉得为您的代码提供更好的方法:我可以到达所有端点

while (true) {
cout << "What day of the week is it?" << endl;
cin >> day;
if (7 < day &&  day < 0 ){
cout << "Invalid day sorry" << endl;
break;
}
cout << "Is it raining? Please type 'yes' or 'no' " << endl;
cin >> rain;
if (0 < day && day < 3) {
if (rain == "yes") {
cout << "Read in bed" << endl;
} else {
cout << "Go out and play!" << endl;
}
} else {
if (rain == "yes")
cout << "Take an umbrella!" << endl;
else
cout << "No umberella needed" << endl;
}
}

这与if语句和多个变量无关,您的0 < day < 3实际上应该读作0 < day && day < 3。顺便说一句,您不需要在同一 if 语句的每个分支中测试它,它不太可能更改。

这不是C++的工作方式:

0 < day < 3

你必须改变它

day > 0 && day < 3