如果我没有正确格式化我的问题,我道歉。我是这个网站的新手,也是编程新手。
我目前正在进行C任务,我相信我已经完成了大部分代码,但是有些调整我似乎无法理解。我将不胜感激任何反馈。这是我的代码
#include <stdio.h>
#include <stdlib.h>
#define SENTINAL -1
double sumOfScores = 0;
double examScore = 0;
double sumOfExams = 0;
double average = 0;
double calculateAverage();
double main(void)
{
int i;
for (i = 1; i <= 4; ++i)
{
calculateAverage();
}
return 0;
}
double calculateAverage()
{
printf("Enter %d to terminate program. \n", SENTINAL);
while(examScore != SENTINAL)
{
printf("Enter test score: \n");
scanf("%lf", &examScore);
sumOfScores += examScore;
sumOfExams++;
average = sumOfScores / sumOfExams;
}
printf("The average of the test scores entered thus far is %.2lf \n\n", average);
return 0;
}
这是我的输出
Enter -1 to terminate program.
Enter test score:
99
Enter test score:
98
Enter test score:
97
Enter test score:
96
Enter test score:
-1
The average of the test scores entered thus far is 77.80
Enter -1 to terminate program.
The average of the test scores entered thus far is 77.80
Enter -1 to terminate program.
The average of the test scores entered thus far is 77.80
Enter -1 to terminate program.
The average of the test scores entered thus far is 77.80
这就是我想要的样子
Enter -1 to terminate program.
Enter test score:
99
Enter test score:
98
Enter test score:
97
Enter test score:
96
Enter test score:
-1
The average of the test scores entered thus far is 77.80
Enter -1 to terminate program.
Enter test score:
95
Enter test score:
94
Enter test score:
93
Enter test score:
92
Enter test score:
-1
The average of the test scores entered thus far is (avg goes here)
我在输出中没有包含额外的两组数字,但我希望能够用四组数字来完成。一旦我输入(-1)终止第一组数字,它就会自动将我的剩余3组的第一组的平均值吐出来,然后我甚至可以输入我想要输入的数字。另外,为什么在第一组价值应该在90年代上涨的时候,它给我的平均值为77.8?
答案 0 :(得分:0)
我建议使用局部变量而不是全局变量。也就是说,移动这些线:
double sumOfScores = 0;
double examScore = 0;
double sumOfExams = 0;
double average = 0;
下面:
double calculateAverage()
{
double sumOfScores = 0;
double examScore = 0;
double sumOfExams = 0;
double average = 0;
// ...
这将导致每次函数启动时变量都重置为0,而不是在上次运行函数时留下垃圾。
我认为您获得错误平均值的原因是您将-1
作为考试成绩之一。您读取该值,然后在检查值是否为-1
之前将其添加到平均值。
printf("Enter test score: \n");
scanf("%lf", &examScore);
// Is examScore equal to -1 here? It might be.
// Don't add it to sumOfScores without checking!
sumOfScores += examScore;
sumOfExams++;
average = sumOfScores / sumOfExams;
您需要在重新计算平均值之前测试值是否为-1
,还是需要重新构建循环,以便在读取和重新计算平均值之间进行examScore != SENTINAL
检查。
另外,严格来说,在循环仍在运行时,无需进行所有平均计算。您可以保存average = sumOfScores / sumOfExams;
行,直到循环结束。只是一个想法。
正如Paul R所说,你的main
函数也有不正确的函数原型。可以找到main
函数的有效原型here