【发布时间】:2019-08-29 04:41:46
【问题描述】:
我正在尝试将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,我的代码也可以工作。
【问题讨论】:
-
有比这更好的编码实践......尝试使用
Invalid day sorry作为中断语句的无限循环。并且可以安全地构建程序以到达所有端点 -
如果一个答案解决了您的问题,那么请考虑支持并标记它已解决。给贡献者一些功劳:)
-
这并不能解决问题,但您不需要在各个比较周围加上括号。
if(0 < day && day < 3 && rain == "yes")和if ((0 < day) && (day < 3) && (rain == "yes"))意思相同。对于有经验的程序员来说,第二个更难阅读,因为你必须停下来弄清楚括号实际上并没有做任何事情。
标签: c++ if-statement comparison-operators