#include <iostream>
using namespace std;
int Age ;
int main(){
cout << "How old are you? ";
cin >> Age;
if (Age < 1)
{
cout << "I dont believe you!";
}
if (Age == 20)
{
cout << "We're almost the same age!" << endl;
}
if (Age == 21)
{
cout << "We're almost the same age!" << endl;
}
if (Age == 22)
{
cout << "We're almost the same age!" << endl;
}
if (Age == 23)
{
cout << "We're almost the same age!" << endl;
}
if (Age == 24)
{
cout << "We're almost the same age!" << endl;
}
if (Age == 25)
{
cout << "We're almost the same age!" << endl;
}
if ( Age % 2 == 1)
{
cout << "Thats an odd age.";
}
cout << "";
}
有什么方法可以更有效地编写一个程序来检查用户年龄是否在 20-25 岁之间,而不是有这么多 if 语句?
我自己尝试在每个数字的条件之间使用 or ,就像这样
if (Age ==20||21||22||23||24||25)
但是没用
最佳答案
if (Age >= 20 && Age <= 25) {
// write your code here
}
if 语句中的 bool 表达式意味着,Age
应该大于或等于
20 和 小于或等于到
25。例如,22 大于 20 且小于 25
。
我建议您阅读有关 logical operators in C++ 的内容.
关于c++ - 更高效地编写 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42197820/