2016-12-05 68 views
1

我应该写一个程序,让用户被问到有多少学生在课堂上。然后,它要求每个学生的GPA。最后,它应该显示每个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); 
} 
+0

首先 - 定义什么是预期的特德。其次 - 描述发生了什么。然后,用调试器遍历你的代码,以确定事情没有起作用。注意:'c'数组开始@零 – KevinDTimm

回答

3

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); 
} 
+1

你错过了所有的最大错误 - 'c'中的数组是基于零的。 – KevinDTimm

+0

好点!但实际上有一个更大的错误:根本不需要GPAFreq! (或者它可以用*代替* cnt1等) –

+0

但是你不知道任务的参数,它可能是他/她班级中数组的第一课。 – KevinDTimm

1

这里有多个错误。首先是cnt1-4必须在被添加之前被初始化。第二个是C使用零索引,所以GPAFreq[4]未访问您的数组的第四个元素(这将是GPAFreq[3]

第三个就是你的if声明没有做什么,你认为它是。这是评估数组内部的值为布尔变量,即0是false,其他任何都是true。更好的方法是这样做: GPAFreq[GPA - 1] += 1; 这将计算阵列中每个索引的频率,然后打印它们,您只需访问GPAFreq并不再需要cnt变量。

+0

最初我没有使用数组,并且它工作得很好。但是,我需要使用数组,但我不知道如何正确使用它们。 –