c++ int switch statement
27,944
Solution 1
You're dividing by 10.0, which is a double and this will not compile. This has to be changed to 10. Also, you should precede the switch statement with an if statement that checks if it's in a valid range.
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int testScore;
cout <<"Enter your test score and I will tell you \n";
cout <<"the letter grade you earned \n";
cin >> testScore;
if (testScore<=100 && testScore>=0)
switch(testScore/10)
{
case 10:
case 9:
cout <<"Your grade is A.\n";
break;
case 8:
cout <<"Your grade is B.\n";
break;
case 7:
cout <<"Your grade is C.\n";
break;
case 6:
cout << "Your grade is D.\n";
break;
case 5:
cout << "Your grade is F.\n";
break;
default:
cout << "That score isn’t valid\n";
}
else
cout <<"That score isn't valid\n";
return 0;
}
Solution 2
You really should do this with 'if' not a 'switch'. Something like the following code (not tested):
if (testScore >=0 && testScore <= 100)
{
char grade;
if (testScore >= 90)
grade = 'A';
else if (testScore >= 80)
grade = 'B';
else if (testScore >= 70)
grade = 'C';
else if (testScore >= 60)
grade = 'D';
else
grade = 'F';
cout << "Your grade is " << grade << endl;
}
else
{
cout << "Score of " << testScore << " is not valid" << endl;
}
Author by
Jose Meza
Updated on February 26, 2020Comments
-
Jose Meza about 4 years
i have been working on a switch for integers for the last hour and a half now, i know how to do switch with char but this seems much hard for me.any advice will be appreciated.the problem i have is that i cant accept grades over 100 which this switch currently does
int testScore; cout <<"Enter your test score and I will tell you \n"; cout <<"the letter grade you earned "; cin >> testScore; switch(testScore/10) { case 10: case 9: cout <<"Your grade is A.\n"; break; case 8: cout <<"Your grade is B.\n"; break; case 7: cout <<"Your grade is C.\n"; break; case 6: cout << "Your grade is D.\n"; break; case 5: cout << "Your grade is F.\n"; break; default: cout << "That score isn’t valid\n"; }
-
Jose Meza about 10 yearsi tried this and it still shows me a grade of A for numbers 100-109
-
jliv902 about 10 yearsThis should be a comment, this does not answer the question.
-
Max Lybbert about 10 yearsIn C++ (and many other languages), dividing the integer
109
by the integer10
returns10
, which will trigger the firstcase
. If you don't want people entering numbers larger than100
, you'll need to enforce that somewhere. For instance, between the line you usecin
and theswitch
statement. -
Seyon about 10 yearsFair enough. In response to the question though, you can have an if statement if (testScore<=100 && testScore>=0) which executes the switch statement if true and outputs Test Score not valid if false
-
jliv902 about 10 years@Borat.sagdiyev You should put that into your answer.