更有效地编写if语句

时间:2017-02-13 06:24:47

标签: c++

#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 (Age ==20||21||22||23||24||25)

但这不起作用

4 个答案:

答案 0 :(得分:8)

if (Age >= 20 && Age <= 25) {
    // write your code here
}

if语句中的布尔表达式表示Age应为greater that or equal to 20 less than or equal to 25。例如,22 is greater than 20 and less than 25。< / p>

我建议你阅读logical operators in C++

答案 1 :(得分:2)

if ((Age >= 20) && (Age <= 25))

答案 2 :(得分:1)

间:

if (Age > 20 && Age < 25)

包括两个限制:

if (Age >=20 && Age <=25)

关闭主题:使用开关案例

switch (Age) {
case 20:
case 21:
case 22:
case 23:
case 24:
case 25:
    cout << "We're almost the same age\n";
    break;
// other cases
}

答案 3 :(得分:1)

使用switch statement。或者也许可以将container映射数量考虑到closures(例如std::map <int,std::function<void(int)> ....),对其进行初始化并访问它以获得应该进行的处理。< / p>

您需要阅读更多有关编程的内容(例如SICP)和C++

花几周时间阅读内容。另请阅读http://norvig.com/21-days.html,了解有关学习编程的有用见解。