我必须编写一个程序来计算具有多个用户输入的 GPA。
如果输入正确,我已经让程序正确计算 GPA,但是,程序还必须进行错误检查,即当输入实际需要为 0、1、2、3 或 4 时用户输入 5。我需要能够告诉用户输入无效并让程序后退一步并允许他们重试。
该程序不能使用数组。
#include <iostream>
using namespace std;
int main ()
{
//Defining variables that will be used during code.
float CreditHours;
int LetterGrade;
float Total;
float TotalCredits = 0;
float TotalPoints = 0;
//Asking for input from user
cout<<"Please enter the grade for your class: 4 for A, 3 for B, 2 for C, 1 for D, 0 for F, or '-1' when you're done inputting grades:\n";
cin >> LetterGrade;
// Logic to ensure valid letter grade input
if ((LetterGrade >= 4) && (LetterGrade <= 0))
{
cout << "Please enter a valid input (0, 1, 2, 3, or 4):\n";
cin >> LetterGrade;
}
cout << "Please enter the credit hours for the previously entered grade: \n";
cin >> CreditHours;
//initializing the loop for more grade inputs
//FIX LOOP
while (LetterGrade != -1)
{
//Updating Totals
Total = LetterGrade * CreditHours;
TotalPoints = TotalPoints + Total;
TotalCredits = TotalCredits + CreditHours;
cout << "Please enter the grade for your class: 4 for A, 3 for B, 2 for C, 1 for D, 0 for F, or -1 when you're done inputting grades:\n";
cin >> LetterGrade;
if (LetterGrade != -1)
{
cout << "Please enter the credit hours for the previously entered grade: \n";
cin >> CreditHours;
}
}//close loop
//Incomplete/Questionable
if (TotalCredits <= 0)
{
cout << "Please be sure your Credit Hours add up to a positive, non-zero value\n";
}
else if (TotalCredits > 0)
{
//Calculating and printing the final GPA.
float gpa = TotalPoints / TotalCredits;
cout << "Your GPA is:"<< gpa <<endl;
}
return 0;