C++ If Else 条件

标签 c++ if-statement

我已经尝试了很长时间,但似乎无法让它发挥作用。该程序不断引用每个输入值的第一个条件。有谁知道代码有什么问题吗?

#include <iostream>

using namespace std;

int main()
{
    int grade;

    cout <<"Enter a grade between 0 and 100:";
    cin>>grade;

    if (0 <= grade <= 59){
        cout<<"The grade for " <<grade<<" is  F";
    }
    else if (60 <= grade <= 69){
        cout<<"The grade for " <<grade<<" is  D";
    }
    else if (70 <= grade <= 79){
        cout<<"The grade for " <<grade<<" is  C";
    }
    else if (80 <= grade <= 89){
        cout<<"The grade for " <<grade<<" is  B";
    }
    else if (90 <= grade <= 100){
        cout<<"The grade for " <<grade<<" is  A";
    }
    system("pause");
    return 0;
}

最佳答案

重写守卫

0 <= grade <= 59

0 <= grade && grade <= 59

C++ 像这样解析你的表达式:

(0 <= grade) <= 59

因此它将 bool 值与 59 进行比较。也就是说, bool 值 true 为 1,并且第一个 if block 被触发

关于C++ If Else 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26231268/

相关文章:

c++ - 如何使用 boost::vf2_subgraph_iso 获取边缘映射

c++ - 如何返回对 'empty' 对象的引用

c++ - qt 图表删除标题/图例/的空间

c++ - 在结构数组上使用 C++ std::copy

javascript - 从函数中获取变量的值

java - IF 在 try block 内

c++ - 左值何时在 C++ 中 move 而不是复制?

c++ - 为什么 switch 和 if 语句与转换运算符的行为不同?

iphone - If 语句不能正确使用 indexpath

python - 创建银行的 IF 中的可变输入。