我必须编写一个用多个用户输入来计算GPA的程序。
如果输入正确,我已经得到了正确计算GPA的程序,但是,程序还必须进行错误检查,即如果用户在输入实际需要为0,1,2,3时输入5,或4.我需要能够告诉用户输入无效并让程序返回一步并允许它们重试。
程序无法使用数组。
#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;
答案 0 :(得分:1)
您可以将if语句更改为while循环,以便在输入有效的数字/数据类型之前程序不会继续。您还可以使用isdigit()来检查输入是否为数字。
答案 1 :(得分:1)
你可以放一段时间:
#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";
while (true)
{
cin >> LetterGrade;
if ((LetterGrade >= 4) && (LetterGrade <= 0))
cout << "Please enter a valid input (0, 1, 2, 3, or 4):\n";
else
break;
}
cout << "Please enter the credit hours for the previously entered grade: \n";
cin >> CreditHours;
答案 2 :(得分:1)
Guga00的答案似乎是正确的。另请注意,您应该更改条件以检查有效的信件。您目前正在检查 LetterGrade 是否大于4且小于0,这将永远不会成立。尝试使用以下内容:
if ((LetterGrade > 4) || (LetterGrade < -1))
我更改了&amp;&amp; (AND)for || (要么)。检查 LetterGrade 是否大于4或小于-1。如果输入无效,它将返回 true 。我添加了-1以允许您检测输入的结束。