Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ If Else conditions

I've been trying this for so long and I can't seem to get this to work. The program keeps referring to the first condition for every input value. Does anyone know whats wrong with the code?

#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;
}
like image 336
vsingh72 Avatar asked May 06 '26 20:05

vsingh72


1 Answers

Rewrite guards

0 <= grade <= 59

with

0 <= grade && grade <= 59

C++ parses your expression like this:

(0 <= grade) <= 59

so it compares bool value with 59. That said, boolean true is 1 and first if block is triggered

like image 89
danbst Avatar answered May 09 '26 11:05

danbst



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!