Else if statments don't work

I'm making a grading program for practice, and no matter what I enter, it always gives me the first if statement.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

using namespace std;

char Grade;

int main()
{
    cout<<"Please enter your grade" <<"\n";
    cin>>Grade;
    if(Grade=9){
        cout<<"You got an A!";
    }else if(Grade=8){
        cout<<"You got a B!";
    }else if(Grade=7){
        cout<<"You got a C";
    }else if(Grade=6){
        cout<<"You got a D";
    }else if(Grade=5){
        cout<<"You got an F";
    }else{
        cout<<"You have failed";
    }

    return 0;
}
Last edited on
closed account (E0p9LyTq)
You need to use if (Grade == x).

http://www.cplusplus.com/faq/beginners/logic/
closed account (E0p9LyTq)
And please, use source code tags to make your source easier to read.

http://www.cplusplus.com/articles/z13hAqkS/
Thank you about the source code, I didn't know how to do that.

Also, using if (Grade == x) only makes it go to the else statment.
Last edited on
You are checking whether the character entered has an ASCII value equal to some number; the characters in the range 9 to 5 are non-printable characters. I suspect what you meant is to check if the user entered the characters 9, 8, etc. In that case, you need to use single quotes to indicate a character literal (e.g., '9').
Nevermind, I fixed it by making "Grades" a string and putting quotation marks around all the numbers. Thanks again for the Source code thing.
closed account (E0p9LyTq)
The if (Grade == x) is simply a shortcut meaning "replace x with a number".
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
   if(Grade==9)
   {
      cout<<"You got an A!";
   }
   else if(Grade==8)
   {
      cout<<"You got a B!";
   }
   else if(Grade==7)
   {
      cout<<"You got a C";
   }
   else if(Grade==6)
   {
      cout<<"You got a D";
   }
   else if(Grade===5)
   {
      cout<<"You got an F";
   }
   else
   {
      cout<<"You have failed";
   }


Also, using if (Grade == x) only makes it go to the else statment.

You are comparing a char variable to numeric values. Use int Grade;

Last edited on
Topic archived. No new replies allowed.