[英]I'm not sure why my variance function returns 0.0000 0.0000
我的程序运行了,但我的 output 应该打印方差和平均值。 有人告诉我,随着我的输入数组大小变得越来越大,我的平均值应该接近 5000,而我的方差应该接近 8333333……但我得到的都是 0。 我唯一能想到的是我错误地填充了我的数据数组/内存块,但如果不是我写的那样,我不知道另一种方法。
#include <stdio.h> //printf
#include <stdlib.h> //malloc, calloc, realloc, free
#include <math.h> //pow
double average_variance(int data[], int numbers, double* varp){
double sum = 0;
//sum of array
for(int i=0; i < numbers; i++){
sum += data[i];
}
double average = sum/numbers;
double squaresum = 0;
//sum of squares
for(int i=0; i < numbers; i++){
squaresum += pow(data[i], 2);
}
//"hack" to return two values by using a pointer; otherwise you can't return two values in a function
double variance = ((squaresum/numbers) - pow(average, 2));
*varp = variance;
return average;
}
int main(int argc, char **argv)
{
int* mydata = NULL;
int arraysize;
while (1)
{
printf("Enter array size (0 to end): "); scanf("%d", &arraysize);
if (arraysize == 0)
break;
// 1. Add code to allocate memory and assign to the mydata // pointer. If mydata is already allocated, use realloc ...
if(arraysize != 0)
{
//used calloc because in the next if statement I needed to see if values were stored in it or not
mydata = calloc(arraysize, sizeof(int));
if (mydata == NULL) {return -1;}
//if mydata array is already allocated use realloc to make a new memory block
if(mydata != 0)
{
mydata = realloc(mydata, arraysize * sizeof(int));
if (mydata == NULL) {return -1;}
}
}
// 2. Add code to put random numbers in the array
for(; mydata < &mydata[-1]; mydata++)
{
int randnum = random() % 10000;
mydata = &randnum;
}
//included
double variance;
double avg = average_variance(mydata, arraysize, &variance);
printf("average = %f variance = %f\n", avg, variance);
}
free(mydata);
数组初始化代码被破坏:
for(; mydata < &mydata[-1]; mydata++)
{
int randnum = random() % 10000;
mydata = &randnum;
}
错误:
mydata[-1]
不是mydata
的最后一个元素(a'la Python),而是数组之前的一个元素。 该元素不存在,未定义的行为被调用。mydata
在初始化期间移动到循环中的局部变量。 这个构造没有希望起作用。做就是了:
for (int i = 0; i < arraysize; ++i)
mydata[i] = random() % 10000;
此外,分配代码是不必要的复杂的。 只需更换:
if(arraysize != 0)
{
//used calloc because in the next if statement I needed to see if values were stored in it or not
mydata = calloc(arraysize, sizeof(int));
if (mydata == NULL) {return -1;}
//if mydata array is already allocated use realloc to make a new memory block
if(mydata != 0)
{
mydata = realloc(mydata, arraysize * sizeof(int));
if (mydata == NULL) {return -1;}
}
}
和:
mydata = realloc(mydata, arraysize * sizeof *mydata);
if (!mydata) return -1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.