除了scanf()
只读取第一个值,然后再根据该值进行计算外,我无法真正解释它。
int main() {
int i, students = 0;
char name[20];
int tests;
float test_score;
int test_sum = 0;
char letter_grade;
double test_average;
printf("Number of students: ");
scanf("%d", &students);
for (i = 0; i < students; i++) {
printf("\nStudent name %d: ", i + 1);
scanf(" %s", &name);
fflush(stdin);
printf("Number of test(s) for %s: ", name);
scanf("%d", &tests);
fflush(stdin);
printf("Enter %d test score(s) for %s: ", tests, name);
if (i < students) {
scanf("%f", &test_score);
test_sum += test_score;
test_average = test_sum / (float)tests;
}
printf("Average test score: %.2f", test_average);
fflush(stdin);
}
return 0;
}
假设我输入2个学生,第一个具有2个测试分数的学生,然后输入4587。我应该得到66.00,但是我得到22.50。对于第二个学生,我输入3个测试成绩100 55 87,我得到48.33。Waaayyy关闭。
我知道我做错了事,但我无法弄清楚,因为我以前曾做过,但是循环不会继续到第二位学生。
if (i < students) {
scanf("%f", &test_score);
test_sum += test_score;
test_average = test_sum / (float)tests;
}
应该 :
test_sum = 0;
for (int j = 0; j < tests; j++) {
scanf("%f", &test_score);
test_sum += test_score;
}
test_average = test_sum / (float)tests;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句