我是大一的学生,学的是c。我正在做作业,但是其中一个循环有问题。我正在使用代码块与GNU GCC编译器。请忽略选项2、3、4。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, numscr;
float grade[2021];
int id[2021];
int opt;
float avg[2021];
float sum=0.0;
do {
printf("nOption 1: Enter student's infon");
printf("Option 2: Print out student's infon");
printf("Option 3: Find the student with the lowest and highest graden");
printf("Option 4: Exitn");
printf("Enter option: ");
scanf("%d", &opt);
if(opt==1)
{
printf("ntEnter the amount of student (Amount>=2): ");
scanf("%d", &num);
printf("tEnter the amount of subject: ");
scanf("%d",&numscr);
for(i=0; i<num; i++)
{
printf("ntEnter student's id: ");
scanf("%d", &id[i]);
for(i=1; i<=numscr; i++)
{
printf("tEnter point of subject %d: " ,i);
scanf("%f", &grade[i]); /*The loop skips here.
After entering the grade for each subject,
it just skips whatever student's id and subject's point there are left.
I think the problem is with the sum+=grade[I]; but I don't know why*/
sum+= grade[i];
}
}
avg[i]=sum/numscr;
}
} while(opt>0 && opt<=3)
return 0;
}
抱歉,如果代码看起来不太好,我忘记格式化它直到现在。如果有人能帮忙的话,我真的很感激,我整个下午都在绞尽脑汁。
您将i
用于for(i=0; i<num; i++)
和for(i=1; i<=numscr; i++)
的两个循环。这意味着内部循环将使用i
并影响外部循环。
使用另一个变量(例如,j
)来修复内部循环。
而且看起来您在计算每个查询的平均值之前忘记初始化sum
了。