For my assignment I'm being asked to write a program that allows a user to input as many grades as they'd like and then calculate only the GPA of only valid entries. I've yet to write the GPA calculation part of the code but what I'm having a hard time with is getting the program to accept decimal numbers as an input for grades. Every time I put in a decimal number, the program quits rather than allowing the user to answer if they'd like to put in another grade.
I'm super new to C++ so sorry for my horrible coding below. Thanks very much!
Oh my lord, lol. This won't even compile will it? You should be using nested if-else statements, and the const variables you are declaring actually aren't variables. Although you are the right track as far as the comparison operations, replace the variables inside the if-elses with what you are trying to declare them to be.
Something like this may be more appropriate:
#include<iostream>
usingnamespace std;
int main()
{
float mark;
cout << "Enter mark for letter grade: ";
cin >> mark;
if(mark < 50)
{
cout << "F" << endl;
}
elseif(mark >= 50 && mark < 60 )
{
cout << "P" << endl;
}
elseif (mark >= 60 && mark < 70)
{
cout << "D" << endl;
}
elseif (mark >= 70 && mark < 80)
{
cout << "C" << endl;
}
elseif (mark >= 80 && mark < 90)
{
cout << "B" << endl;
}
else //small change, if we reached this point, we can assume the grade is A, no need to test for it.
{
cout << "A" << endl;
}
}
Thanks for the suggestions. I'll try them out. It does actually compile and run but I was having some issues with certain inputs like I said.
My instructor indicated that no hard coding values were to be used in the program and to use variables as much as possible -- especially for the grade values. It ran a lot better when I used values but alas, I'm not allowed to.
My instructor indicated that no hard coding values were to be used in the program and to use variables as much as possible -- especially for the grade values.
That's good advice.
@Mr D
It's also a good idea to use the else part of an if else chain to catch errors. In this case if the input is > 100 Or < 0.
34 35 36 37
else //small change, if we reached this point, we can assume the grade is A, no need to test for it.
{
cout << "A" << endl;
}
elseif (mark >= 90 && mark <= 100) //use variables for the 90 and 100 and the others elsewhere
{
std::cout << "A\n";
}
else // mark is negative or > 100
{
std::cout << "Error, Input out of range.\n";
}
Although an even better idea is to validate the input before doing any other code that uses it. Validating data is a very important concept in coding. Despite doing that, it is still a good idea to use the else as error check anyway.
@skyllianfive
Another thing: if you find yourself writing the same code over and over (as in your OP) then it can be done better.
Try to avoid having usingnamespace std; Google to see why that is so, and what to do instead.