ocelot ocelot - 20 days ago 6
C++ Question

C++: Displaying a saved char value to screen

Whenever the below c++ program below is run, I keep getting the same output which is " A ", even if I enter a grade value of say, 84, or 76. I am confused as to why the output is always " A" and not the grade letter value it should be based off the number grade input. I know it is most likely a logical error in my code, but I cant seem to understand why.

char letterGrade;
int scoreGrade;

cout << "Enter Course Name: ";
cin >> courseName;

cout << "Score Grade Recieved: ";
cin >> scoreGrade;
while (scoreGrade < 0 || scoreGrade > 100) {
cout << "Invalid Entry, Enter Score Grade: ";
cin >> scoreGrade;
}

if (scoreGrade >= 90 || scoreGrade <= 100) {
letterGrade = 'A';
}
else if (scoreGrade >= 80 || scoreGrade < 90) {
letterGrade = 'B';
}
else if (scoreGrade >= 70 || scoreGrade < 80) {
letterGrade = 'C';
}
else if (scoreGrade >= 60 || scoreGrade < 70) {
letterGrade = 'D';
}
else
letterGrade = 'F';

cout << letterGrade;

Answer

your conditions are being evaluated to true every time.

if (scoreGrade >= 90 || scoreGrade <= 100)

Evaluates to true no matter what value is entered. This is saying if the value is greater than or equal to 90 or the value is less than 100. You should use the && operator instead of || which would change the statement to greater than or equal to 90 and the value is less than 100

Comments