我试图得到这个代码来计算一个类的平均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;
}发布于 2015-06-19 20:50:48
这里有两个问题。首先,您需要丢弃扫描程序上的新行。详情请参见这里。
其次,无论用户输入y或y,都会使整条语句的计算结果变为true。尝试切换到A &&操作符,并在他们自己的括号内关闭这两个检查。
看下面的例子-它至少会让你更进一步,尽管我仍然没有从你的数学中得到正确的答案。
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;发布于 2015-06-19 20:53:05
在底部的检查中,你的逻辑有点错误。
如果你说Y或y,或者班级规模达到30,就应该结束。
这意味着:
while(x < 30 || cResp != 'y' || cResp != 'Y')https://stackoverflow.com/questions/30946623
复制相似问题