c++ - 更高效地编写 if 语句

标签 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 语句?

我自己尝试在每个数字的条件之间使用 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/

相关文章:

c++ - 为什么移动 vector 不触发移动内部元素?

c++ - C++中的PLC功能 block 库

c++ - 使用 CRTP 时如何避免错误?

c++ - 如何在 VSCode 上设置数据断点(即观察点)

c++ - WriteFile 什么都不做

c++ - 什么决定了调用 delete 时写入 C++ 指针的内容?

Android OpenCV - 将 OpenCV C++ 代码转换为 Android 以检测 QR 码对齐方 block

c++ - 找到 $number 然后用 $number+1 替换它?

c++ - Windows C++框架推荐

c++ - 从 QThread 与 QProcess 通信