How to get if else statements to work.

The code is good up until I get to the 'if' part. When I run the code, lets say I enter the numbers: 90, 80 and 70. It will read

The average is 80
The letter grade is A
The letter grade is F


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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include<iostream>
using namespace std;

int main()
{ 
    double ts1 = 0.0;
    cout << "Enter testscore1 within range of 0 and 100: ";
    cin >> ts1;
  
    while (ts1 < 1 || ts1 > 100) {
       cout << "Error: Re-enter testscore1 within range of 0 and 100: ";
       cin >> ts1;
    }
    double ts2 = 0.0;
    cout << "Enter testscore2 within range of 0 and 100: ";
    cin >> ts2;

    while (ts2 < 1 || ts2 > 100) {
        cout << "Error: Re-enter testscore2 within range of 0 and 100: ";
        cin >> ts2;
    }
    double ts3 = 0.0;
    cout << "Enter testscore3 within range of 0 and 100: ";
    cin >> ts3;

    while (ts3 < 1 || ts3 > 100) {
        cout << "Error: Re-enter testscore3 within range of 0 and 100: ";
        cin >> ts3;
    }
    
    double avg = ( ts1 + ts2 + ts3)/3;
    cout << "The average is " << avg << endl;

    if (avg < 90 || avg > 100)
     {
        cout << "The letter grade is A" << endl;
     }
    else if (avg < 80 || avg > 89)
     {
        cout << "The letter grade is B" << endl;
     }
    else if (avg < 70 || avg > 79)
     {
        cout << "The letter grade is C" << endl;
     }
    else if (avg < 60 || avg > 69)
     {
        cout << "The letter grade is D" << endl;
     }
    else (avg < 60);
     {
        cout << "The letter grade is F" << endl;
     }

    return 0;
} 
Hi,

Your conditions are wrong, try for example :

34
35
36
37
38
39
40
41
if (avg >= 90.0 && avg <= 100.0) // put decimal points and trailing zero for numbers which are double
     {
        std::cout << "The letter grade is A\n";
     }
else if (avg >= 80.0 && avg < 90.0)
     {
         std::cout << "The letter grade is Bn";
     }


An else cannot have a condition, and watch for extraneous semicolons on line 50.

Consider using an array (have you learnt about them yet? :+) ) and for loops to process them.

Good Luck!!

Edit: if you want to use whole numbers, cast the avg to an unsigned int:

AverageAsInt = static_cast<unsigned int>(avg);
Last edited on
if (avg < 90 || avg > 100)
If avg is 80, then it is less than 90, so (avg < 90 || avg > 100) is true.

1
2
3
4
    else (avg < 60);
     {
        cout << "The letter grade is F" << endl;
     }

The semicolon is screwing things up - that's the equivalent of writing:

1
2
3
4
5
    else
     {
         (avg < 60);
     }
    cout << "The letter grade is F" << endl;

Last edited on
Topic archived. No new replies allowed.