2

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;
}
cfrick
  • 35,203
  • 6
  • 56
  • 68
vsingh72
  • 23
  • 2
  • On a sidenote, take a look at [this question about system("pause")](http://stackoverflow.com/questions/1107705/systempause-why-is-it-wrong). – risingDarkness Oct 07 '14 at 09:15

3 Answers3

10

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

danbst
  • 3,363
  • 18
  • 38
1

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.

chiastic-security
  • 20,430
  • 4
  • 39
  • 67
1

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

Deb
  • 2,922
  • 1
  • 16
  • 32