C++ switch statement beginner exercise | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
0

C++ switch statement beginner exercise

Can anyone please explain to me where is the error? I can't really understand😂 This is the exercise: "Write a program that allows the user to enter the grade scored in a programming class (0-100). Modify the program so that it will notify the user of their letter grade using switch statement. 0-59 F 60-69 D 70-79 C 80-89 B 90-100 A." And this is my code: #include <iostream> using namespace std; int main() { int grade=0; cin>>grade; switch (grade) { case 50&&59: cout<<"You've got a F"; break; case 60&& 69: cout<<"You've got a D"; break; case 70&&79: cout<<"Yuo've got a C"; break; case 80&&89: cout<<"Yuo've got a B"; break; case 90&&99: cout<<"Yuo've got an A"; break; } return 0; }

24th Nov 2018, 2:44 PM
Martina
1 Réponse
+ 5
Switch as per the standards does not work for ranges. A&&B is of type bool, and bool variables can hold either a true or a false. These can be converted to a 1 or a 0. So your switch block translates to : switch (grade) { case 1: cout<<"You've got a F"; break; case 1: cout<<"You've got a D"; break; case 1: cout<<"Yuo've got a C"; break; case 1: cout<<"Yuo've got a B"; break; case 1: cout<<"Yuo've got an A"; break; } Since all the case values are the same, the compiler throws an error. To solve this problem, use an if else-if ... else combination. if(grade<=59&&grade>=50) cout<<"You've got a F"; else if(grade<=69&&grade>=60) cout<<"You've got a D"; // Other cases follow. // Base case for the last option. else cout<<"You've got an A"; If you have GNU GCC as your compiler, you can also use case ranges unique to GCC: switch(grade) { case 50...59: cout<<"You've got a F"; break; // The rest of the cases follow. }
24th Nov 2018, 2:54 PM
Kinshuk Vasisht
Kinshuk Vasisht - avatar