我正在从一本名为“C by Example”的书中学习C
每章结尾都有一个练习要完成。从下面的代码中可以看出,练习写在顶部
/* Chapter 7 Review Exercises #2
- You are a college professor and you have to get the average grades for 10 students. Write a program which prompts you for 10 different grades and then
displays their average */
#include <stdio.h>
int main()
{
float score1, score2, score3, score4, score5, score6, score7, score8, score9, score10;
float average = score1+score2+score3+score4+score5+score6+score7+score8+score9+score10/10;
printf("Please input the scores of the students: \n");
scanf(" %f",&score1);
scanf(" %f",&score2);
scanf(" %f",&score3);
scanf(" %f",&score4);
scanf(" %f",&score5);
scanf(" %f",&score6);
scanf(" %f",&score7);
scanf(" %f",&score8);
scanf(" %f",&score9);
scanf(" %f",&score10);
printf("The average score is: %.2f" , average);
return 0;
}
这里的问题是每次我输入数字(运行代码时)它总是给我一个巨大的数字(至少20个数字)
有没有办法限制数量,或者我做错了什么?
答案 0 :(得分:3)
你在这里遗漏了一些括号:
float average = score1+score2+score3+score4+score5+score6+score7+score8+score9+score10/10;
将其更改为:
float average = (score1+score2+score3+score4+score5+score6+score7+score8+score9+score10)/10;
您还需要将此行向下移动,以便在输入阶段之后(即在所有对scanf
的调用之后),因为尝试计算某些内容是没有意义的之前您拥有所有输入值。
您可能想要了解运算符优先级,也可以循环,因为您的程序可以更简单,更简洁地编写:
#include <stdio.h>
int main()
{
const int n = 10;
float sum = 0.0f;
float average;
int i;
printf("Please input the scores of the students: \n");
for (i = 0; i < n; ++i)
{
float score;
scanf(" %f", &score);
sum += score;
}
average = sum / n;
printf("The average score is: %.2f" , average);
return 0;
}
答案 1 :(得分:1)
这个数字确实是错误的,因为你不了解C如何执行代码。它最适合botom。因此,如果您需要得分1 ...得分10的值,则首先需要执行scanf
,然后才能使用+
。
答案 2 :(得分:1)
以下代码可以使用。您的代码无法正常工作,因为您尝试在扫描之前计算数字。仍然需要记住,C保持操作的顺序,因此/
在+
之前执行。添加缺少的括号()
。在C中,代码从顶部到底部处理!
#include <stdio.h>
int main() {
float score1, score2, score3, score4, score5, score6, score7, score8, score9, score10;
printf("Please input the scores of the students: \n");
scanf(" %f",&score1);
scanf(" %f",&score2);
scanf(" %f",&score3);
scanf(" %f",&score4);
scanf(" %f",&score5);
scanf(" %f",&score6);
scanf(" %f",&score7);
scanf(" %f",&score8);
scanf(" %f",&score9);
scanf(" %f",&score10);
float average = (score1+score2+score3+score4+score5+score6+score7+score8+score9+score10)/10;
printf("The average score is: %.2f" , average);
return 0;
}