If Statements With Multiple conditions

1
2
3
4
5
6
7
8
9
char grade = 'F' ;

if( avg_grade >= 89.5 ) grade = 'A' ; // >= 89.5 A
else if( avg_grade >= 79.5 ) grade = 'B' ; // 79.5 – 89.4999... B
else if( avg_grade >= 69.5 ) grade = 'C' ; // 69.5 – 79.4999... C
else if( avg_grade >= 59.5 ) grade = 'D' ; // 59.5 – 69.4999... D
// else grade remains 'F' ;

std::cout << "grade: " << grade << '\n' ;

This is not the first time this problem has cropped up.
The usual reason for having problems with this is going straight to coding without a plan such as pseudocode or even better a flow chart.

Try this pattern (untested - your job) where there is a downward cascade, and doing the printing at the end instead of repeating the cout's needlessly:

1
2
3
4
5
6
7
8
9
10
11
char letter;
    
    if(grade >= 89.5)
        letter = 'A';
    else if (grade >= 79.5)
        letter = 'B';
    
    ... etc etc
    
    else
        letter = 'F';
Topic archived. No new replies allowed.