[英]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.