我应该写一个程序,在这个程序中,用户会被问到一个班级有多少学生。然后,它要求每个学生的GPA。最后,它应该显示每个GPA分数的学生数量。到目前为止,这就是我所拥有的,但它似乎不能正确地计算。
#include <stdio.h>
int main(void){
int cnt1, cnt2, cnt3, cnt4, student, numofsdts, GPA, GPAFreq[4];
printf("Enter number of students: ");
scanf("%d", &numofsdts);
student = 1;
while(student <= numofsdts){
printf("GPA of student number %d: ", student);
scanf("%d", &GPA);
if(GPA < 1 || GPA > 4){
printf("invalid number \n");
}
else{
student++;
}
if(student == numofsdts + 1)
break;
if(GPAFreq[1])
cnt1++;
else if(GPAFreq[2])
cnt2++;
else if(GPAFreq[3])
cnt3++;
else if(GPAFreq[4])
cnt4++;
}
printf("GPA 1: %d students \n", cnt1);
printf("GPA 2: %d students \n", cnt2);
printf("GPA 3: %d students \n", cnt3);
printf("GPA 4: %d students \n", cnt4);
}发布于 2016-12-06 03:29:44
设置int cnt1 = 0, cnt2 = 0等(它们在默认情况下不是无效的,只是有一些垃圾,比如租来的房间没有显式清理……)。
另外:
if(GPA < 1 || GPA > 4){
printf("invalid number \n");
continue; // skip the rest of the loop body
}或者一种稍微干净一点的方法(完整的):
#include <stdio.h>
int main(void){
int cnt1 = 0, cnt2 = 0, cnt3 = 0, cnt4 = 0;
int numofsdts, GPA;
printf("Enter number of students: ");
scanf("%d", &numofsdts);
students = 0;
while(students <= numofsdts){
printf("GPA of student number %d: ", students + 1);
scanf("%d", &GPA);
if(GPA < 1 || GPA > 4){
printf("invalid number \n");
continue;
}
if(GPA == 1)
cnt1++;
else if(GPA == 2)
cnt2++;
else if(GPA == 3)
cnt3++;
else if(GPA == 4)
cnt4++;
students++;
}
printf("GPA 1: %d students \n", cnt1);
printf("GPA 2: %d students \n", cnt2);
printf("GPA 3: %d students \n", cnt3);
printf("GPA 4: %d students \n", cnt4);
}发布于 2016-12-06 03:34:27
这里有多个错误。第一个问题是,在添加cnt1-4之前,必须对其进行初始化。第二个原因是C使用零索引,所以GPAFreq[4]不会访问数组的第四个元素(应该是GPAFreq[3]。
第三个问题是您的if语句没有执行您所认为的操作。它将数组中的值作为布尔变量进行求值,即0为false,其他值为true。一种更好的方法是这样做:GPAFreq[GPA - 1] += 1;,这将计算阵列的每个索引中的频率。然后,要打印它们,只需访问GPAFreq,而不再需要cnt变量。
https://stackoverflow.com/questions/40981823
复制相似问题