所以我的 C 代码没有正确读取传递到我创建的库函数的数组。它出于某种原因输出 4 号,当它是 10 号时,等等。请帮助我完成这项工作。该库包含在文件头中。
int main()
{
// data of array
double input[] = {30.0, 90.0, 100.0, 84.0, 72.0, 40.0, 34.0, 91.0, 80.0, 62.0};
// size of array
int size = sizeof(input)/sizeof(double);
// getting information from library based on data of array
printf("The mean is: %.2f", calculateMean(size, input));
}
//这是图书馆 //返回数据的平均值
double calculateMean(int totnum, double data[])
{
double total = 0;
int size = sizeof(data)/sizeof(double);
for(int i=0; i<size; i++)
{
total += data[i];
}
return (double)total/size;
}
最佳答案
在 calculateMean
中你使用
int size = sizeof(data)/sizeof(double);
获取数据
的大小。但是数组作为指针传递给函数。
所以你的 size
可能被初始化为 0
(在大多数平台上 sizeof(double) > sizeof(double*)
)
您将 totnum
传递给函数但不使用它。使用它你可以解决问题
double calculateMean(int totnum, double data[])
{
double total = 0;
for(int i=0; i<totnum; i++)
{
total += data[i];
}
return (double)total/totnum;
}
关于c - 测试文件到库文件,数组没有被正确读入 c 中的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33104931/