我编写了一种方法来获取数组(通过指针)及其大小来计算平均值。我对指针还比较陌生。我尝试将整个代码中的引用运算符删除到可以编译的程度,但返回的值不是预期的。例如,如果我传入的数组大小为 3,然后我的数组值为 {1, 2, 3},闭上眼睛我可以告诉你平均值应该是 2。但是我的代码返回 2.666666667。反过来想,我将 2.6666...7 乘以 3,等于 8。这让我认为我在某个地方,将 2 修改为数组,例如 {1,2,3,2},但是我'我现在不确定。如果有人对指针/简单算术有任何经验,我会很感激你的建议,因为同样,我对指针和按地址引用的想法很陌生。谢谢!
double *Average(double *arr, int size)
{
double *avg;
avg = (double *)malloc(sizeof(double));
*avg = 0;
int i;
for (i = 0; i < size; i++)
{
*avg = *avg + arr[i];
}
*avg = *avg / (double) size;
printf("The average of the array: %f\n", *avg);
return avg;
}
如何从 main 调用该方法:
else if (choice == 'C' || choice == 'c')
{
int count;
printf("How many numbers do you want to use in the array?\n> ");
scanf("%d", &count);
double *arr;
arr = (double *)malloc(sizeof(double) * count);
int i;
for (i = 0; i < count; i++)
{
printf("Please enter a number (%d of %d)\n> ", i + 1, count);
scanf("%lf", &arr[i]);
}
Min(arr, count);
Max(arr, count);
Average(arr, count);
}
测试:
- 平均({1,3,5}, 3)
Expected: 3, Got: 4.333333
- 平均({1,1,1}, 3)
Expected: 1, Got: 1
- 平均值({1,2,3,4,5,6,7,8,9}, 9)
Expected: 5, Got: 5.888889
每个用户请求两个额外的方法:
double *Min(double *arr, int size)
{
double *min = &arr[0];
int i;
for (int i = 1; i < size; i++)
{
if (arr[i] < *min)
{
*min = arr[i];
}
}
printf("Smallest number in array: %f\n", *min);
return min;
}
double *Max(double *arr, int size)
{
double *max = &arr[0];
int i;
for (int i = 1; i < size; i++)
{
if (arr[i] > *max)
{
*max = arr[i];
}
}
printf("Largest number in array: %f\n", *max);
return max;
}
最佳答案
问题就在这里,纠正这个:
*max = arr[i];
您正在将 *max
(即 arr[0]
)更改为数组的最大值或最小值。因此,当 Average()
函数获取数组时,它不是您输入的数组,而是已更改。例如:
Max({1,3,5})=5
数组变成:
arr={5,3,5}
正确的平均值是:
Average({5,3,5} = 4.3333
关于c - 为什么我的数字数组的平均值不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52305650/