我需要编写一个 C 程序来读取类(class)中的学生人数(1<=students<=25
),并让每个学生读取他的考试成绩 ex 10/20
15/20
etc( 1<=score<=20
) 并打印学生的最高分和最高分以及类(class)的平均分。
我编写了程序,但它执行了 for
由于某种原因只循环一次。
你能帮我理解为什么吗?
代码如下:
#include <stdio.h>
int main(void) {
int m,i,b,sum,min,max,mo;
sum=0;
while (m<1 || m>25) {
printf("give number of students ");
scanf("%d",&m);
}
for (i=1; i<(m+1); i++) {
while (b<1 || b>20) {
printf("give score of %d student",i);
scanf("%d",&b);
}
if(i==1) {
min=b;
max=b;
}
else {
if(b<min) min=b;
if(b>max) max=b;
}
sum=sum+b;
}
mo=sum/m;
printf("max is %d and min is %d and avg is %d",max,min,mo);
}
最佳答案
首先 - 初始化您的变量:
int m,i,b,sum,min,max,mo; // these are declared and uninitialized
m = 0; // now it's initialized to 0
i = 0;
...
如果您不将它们初始化为某物,您将不知道它们是从什么开始的。
其次 - 您需要更改 b
的值:
for (i=1; i<(m+1); i++) {
while (b<1 || b>20) { <-- here you're checking for b being valid
printf("give score of %d student",i);
scanf("%d",&b);
}
所以 b 中的第一次将在 1 到 20 之间,如果你不将它重置为无效的值,你将永远不会再次到达这里。记录 b 的值后:
sum=sum+b;
b = 0; // we're done with b for now, set it to something invalid for the while()
}
关于c - for 循环将只执行一个循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13313921/