Hello, I'm currently taking a C++ course which I thought would be a worthwhile class. I know how to do switch statements with a single character as the case. However when it comes to checking a variable for numerical conditions with case it's a completely different story. My instructor wants me to correct the errors with the code below, but I am clueless what to change it to. The book only covers switch case statements with a single character.
Normally in this case I would just use if, else if, and else (if needed) but for the other questions where I had to find errors they never made me change the whole script completely so I am a bit against using it.
Some suggestions on what to change it to and an explaination would be greatly appreciated.
The error I receive when I input the code they provided
error: 'testScore' cannot appear in a constant-expressi
on
//This program uses a switch-case statement to assign
//letter grades to a numeric testScore
#include <iostream>
usingnamespace std;
int main()
{
int testScore;
cout <<"Enter your test score and I will tell you\n";
cout <<"the letter grade you earned: ";
cin>> testScore;
switch (testScore)
{
case (testScore < 60.0):
cout << "Your grade is F.\n";
break;
case (testScore < 70.0):
cout << "Your grade is D.\n";
break;
case (testScore < 80.0):
cout << "Your grade is C.\n";
break;
case (testScore < 80.0):
cout << "Your grade is B. \n";
break;
case (testScore < 90.0):
cout <<"Your grade is A.\n";
default:
cout << "That score isn't valid\n";
return 0;
}
}
The condition within a case has to be a constant-expression.
case (testScore < 90.0) is wrong because testScore < 90.0 could be true OR false; has MORE THAN one outcome. case (90) is correct because it has ONLY one outcome which is 90
To do this in a switch statement, you would need to have about 60 cases. An if-else would be better.