具有多个变量的 if 语句
If statements with multiple variables
我正在尝试使用具有多个比较操作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 bed
或go 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 < 3
C++计算其中一个,然后比较变成布尔<整数>整数>
我觉得为您的代码提供更好的方法:我可以到达所有端点
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
相关文章:
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- 以在Qt中的IF语句中设置时间延迟
- Craps游戏问题,忽略if语句
- c++:定义if语句中的模板
- C++嵌套的 If 语句中,它无法按预期工作
- 如果条件不相关,我应该更喜欢两个 if 语句而不是 if-else 语句吗?
- 需要有关此 if 语句的帮助
- 转换器练习:跳过 if 语句和 if 语句
- 避免在 C++ 中的 if 语句中递增
- 如果仍然不满足要求,如何使 if 语句重复?
- do while 循环中的 if 语句以 yes 或 no 结尾
- 为什么在此C++代码中触发此 if 语句?
- 如何基于平台在制作文件中制作if语句?
- 在 if 语句中使用 GetKeyState 时,它会跳过条件
- C++ If 语句,从其他语句重复