C中的GPA计算器

时间:2015-06-19 20:19:46

标签: loops for-loop do-while

我正在尝试使用此代码来计算班级的平均GPA。我遇到的问题是我似乎在我的do...while代码中犯了一个错误,因为当我运行它时,它会不断循环回来让我输入另一个GPA,而不是问我是否想要计算平均值与否。

#include<stdio.h>

int main()
{
    float faGPA[30], fSum = 0, fAvg = 0;
    int x, y;
    char cResp = '\0';

    printf("\t\tGPA Calculator\n");
    printf("\nEnter up to 30 GPAs into the calculator.\n");

    do{
        printf("\nEnter a GPA: ");
        scanf("%f", &faGPA[x]);
        x++;
        printf("\nCalculate the GPA average (Y/N)?\n");
        scanf("%c", &cResp);
    } while(x < 30 && cResp != 'Y' || x < 30 && cResp != 'y');

    for(y = 0; y < (x + 1); y++)

    fSum += faGPA[y];
    fAvg = (fSum / (y - 1));

printf("\nThe class GPA is:%.2f", fAvg);

return 0;
}

2 个答案:

答案 0 :(得分:2)

这里有两个问题。首先,您需要在scanf上丢弃新行。有关详细信息,请参阅here

第二个||无论用户是否已输入Y或y,运算符都将使整个语句评估为true。尝试切换到&amp;&amp;运算符并在它们自己的括号中关闭两个检查。

请参阅下面的示例 - 它至少应该让您更进一步,但我仍然没有从您的数学中得到正确答案。

float faGPA[30], fSum = 0, fAvg = 0;
int x = 0, y = 0;
char cResp = '\0';

printf("\t\tGPA Calculator\n");
printf("\nEnter up to 30 GPAs into the calculator.\n");

do{
    printf("\nEnter a GPA: ");
    scanf("%f", &faGPA[x]);
    x++;
    printf("\nCalculate the GPA average (Y/N)?\n");
    scanf("\n%c", &cResp);
} while (x < 30 && (cResp != 'Y' && cResp != 'y'));

for (y = 0; y < (x + 1); y++)

    fSum += faGPA[y];
fAvg = (fSum / (y - 1));

printf("\nThe class GPA is:%.2f", fAvg);

return 0;

答案 1 :(得分:2)

你在底部支票的逻辑有点偏。

如果你说Y或y,或者班级人数达到30,那就应该结束。

这转换为:

while(x < 30 || cResp != 'y' || cResp != 'Y')