0

我必须编写一个程序来计算具有多个用户输入的 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;
4

3 回答 3

1

您可以将 if 语句更改为 while 循环,以便程序在输入有效数字/数据类型之前不会继续。您还可以使用 isdigit() 检查输入是否为数字。

于 2013-09-24T19:21:14.390 回答
1

你可以设置一个while条件:

#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;
于 2013-09-24T19:23:51.290 回答
1

Guga00 的答案似乎是正确的。另外,请注意,您应该更改您的条件以检查有效的信件。您当前正在检查LetterGrade是否既大于 4 又小于 0,这永远不会是真的。尝试使用以下内容:

if ((LetterGrade > 4) || (LetterGrade < -1))

我为 || 更改了 && (AND) (或者)。这会检查LetterGrade是大于 4 还是小于 -1。如果输入无效,它将返回true 。我添加了 -1 以允许您检测输入的结束。

于 2013-09-24T19:46:50.843 回答