vsingh72
vsingh72

Reputation: 23

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;
}

Upvotes: 2

Views: 146

Answers (3)

chiastic-security
chiastic-security

Reputation: 20520

You can't write 0 <= x <= 59 in that way. Or rather, you can, but it doesn't mean what you think it means.

It gets analyzed like this. 0 <= x is evaluated, and determined to be either true or false. These booleans are represented by 1 or 0 respectively. Then the resulting 1 <= 59 or 0 <= 59 gets evaluated, and will always be considered true.

As an aside, it's things like this that I think make Java a good language to start out with when you're learning to program. It's strongly typed, which roughly means things like this generate compile-time errors rather than doing something you didn't really mean.

Upvotes: 1

Deb
Deb

Reputation: 2972

You are doing it wrong for checking range condition. The right way to measure range is to use && operator.

Do something like this:

if (grade>=0 && grade <= 59)  // it means grade is greater or equal to 0 and grade is lesser or equal to 59 

replace similar for every if condition

Upvotes: 1

danbst
danbst

Reputation: 3613

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

Upvotes: 10

Related Questions