Alright, this is a refresher assignment for my Advanced C++ class, and I have the program doing everything it is supposed to, except it is not recognizing the correct grade when I put in a decimal, such as 59.6. I thought that I would have to use a float type for the grade, but I cannot use float with switch/case statements, which he required us to use. Why is it not working correctly, or how could I fix it?
// Assignment One - Kara Pardue
// 1/20/2012
// This program should ask the user for their name and their numerical grade.
// It should then use if/else statements to determine the letter grade.
// After this, it should use switch/case statements to print the user's name and letter grade.
// If the letter grade is not between 0 and 100, the program should ask the user to re-enter their grade.
#include<iostream>
#include <string>
usingnamespace std;
int main()
{
string name;
int grade;
cout << "Please enter your name." << " ";
cin >> name;
cout << "Please enter your numerical grade." << " " ;
cin >> grade;
if (grade < 0 || grade > 100)
{cout << "Numerical grade must be 0 to 100." << endl;
cout << "Please re-enter your numerical grade." << " ";
cin >> grade;
}
if(grade >= 89.5 && grade <= 100)
grade = 'A';
elseif(grade >= 79.5 && grade < 89.5)
grade = 'B';
elseif(grade >= 69.5 && grade < 79.5)
grade = 'C';
elseif(grade >= 59.5 && grade < 69.5)
grade = 'D';
elseif (grade < 59.5 && grade >= 0)
grade = 'F';
switch (grade)
{
case'A' : cout << "Hello, " << name << "! Your grade is an A." << endl;
break;
case'B' : cout << "Hello, " << name << "! Your grade is a B." << endl;
break;
case'C' : cout << "Hello, " << name << "! Your grade is a C." << endl;
break;
case'D' : cout << "Hello, " << name << "! Your grade is a D." << endl;
break;
case'F' : cout << "Hello, " << name << "! Your grade is an F." << endl;
}
system("pause");
return 0;
}
If you have to do it like that you could just make grade a float and then use a different char variable to hold the letter grade and do the switch statements on.
float percent;
char grade;
// Your cin stuff
if (percent > 89.5 && percent <=100)
grade = 'A';
// other if statments
switch (grade)
//Keep this stuff the same