所以我正在编写统计计算器程序,我开始编写的第一个函数是均值计算器。我的问题是,我得到的答案值非常大(和错误)。
Please Enter a number of inputs
4
Please enter number 1
1
Please enter number 2
2
Please enter number 3
3
Please enter number 4
4
Statistical Calculator Menu
(1) Mean
(2) Standard Deviation
(3) Range
(4) Restart/Exit
1
3940705125981218000000000000000000.000000
这是我的源代码。
const int MAX_DATA=5;
void menu(float numbers[], int amount);
float mean(float numbers[],int amount);
int main()
{
int i, amount;
float numbers[MAX_DATA];
printf("Please Enter a number of inputs \n");
scanf("%d", &amount);
if (amount>MAX_DATA){
printf("You entered too many numbers");
}else{
for (i=1;i<amount+1;i++){
printf("Please enter number %d\n", i);
scanf("%f",&numbers[i]);
}
menu(numbers,amount);
}
getch();
return 0;
}
void menu(float numbers[],int amount)
{
int input2;
printf("Statistical Calculator Menu");
printf("\n(1) Mean\n(2) Standard Deviation\n(3) Range\n(4) Restart/Exit");
scanf("%d",&input2);
if(input2==1){
mean(numbers,amount);
}
}
float mean(float numbers[],int amount)
{
int i;
float sum;
float average;
for (i=0; i<amount;i++){
sum=sum+numbers[i];
}
average=sum/amount;
printf("%f", average);
return average;
}
有人可以指出错误,或解释为什么这不能正确计算?
答案 0 :(得分:4)
您没有初始化sum
所以它会占用堆栈中该位置的最后一个垃圾值。变化:
float sum;
要:
float sum = 0;
你遇到的另一个问题是:
for(i = 1; i < amount + 1; i++) {
printf("Please enter number %d\n", i);
scanf("%f",&numbers[i]);
}
数组索引从0开始,所以这应该是:
for(i = 0; i < amount; i++) {
printf("Please enter number %d\n", i);
scanf("%f",&numbers[i]);
}
答案 1 :(得分:1)
除了迈克所说的,
for (i=1;i<amount+1;i++)
{
printf("Please enter number %d\n", i);
scanf("%f",&numbers[i]);
}
float mean(float numbers[],int amount)
{
// ..
for (i=0; i<amount;i++){
sum=sum+numbers[i];
}
....
从此,您没有填写numbers[0]
。但是在mean
计算中,使用0索引处的值。
答案 2 :(得分:0)
float sum;
float average;
for (i=0; i<amount;i++){
sum=sum+numbers[i];
}
sum
未在您的计划中初始化。