我在制作一个使用函数调用的程序来查找二维数组中行的平均值时遇到问题?我不能让它在更大的程序中工作。我做了这个程序试图弄清楚我做错了什么,但无济于事。任何外界的帮助将不胜感激!这是测试代码:
#include <stdio.h>
double dAvg(double pt[][5],int rows);
int main(void){
int i;
//Initiallize array
double array[3][5]={{3.0,5.0,2.0,1.0,0.0},{4.0,8.0,6.0,3.0,3.0},{7.0,6.0,2.0,3.0,5.0}};
//Computes the average value per row of array
for(i=0;i < 3;i++){
printf("The average of row %d is %f",i,dAvg(array,3));
}
return 0;
}
double dAvg(double pt[][5],int rows){
int r,c;
double sum,avg;
//Calculate sum first
for (c=0,sum=0;c<5;c++){
sum += pt[r][c];
//Find average by dividing the sum by the number of numbers in a row
avg=sum/5;
return avg;
}
}
当我运行该程序时,它只是说该程序已经停止工作,除此之外,我不相信我会在第一个问题解决后实际工作。我对多维数组很新,尤其是将它们传递给函数。再次感谢您的帮助!
答案 0 :(得分:1)
您的dAvg
函数中存在大多数错误:
即:
r
未被初始化,因此您的索引无法正常工作double dAvg(double array[], size_t length){
size_t c;
double sum = 0;
// Calculate sum first
for (c = 0; c < length; c++){
sum += array[c];
}
// Find average by dividing the sum by the number of numbers in a row
return sum / (double) length;
}
int main(void){
int i;
//Initiallize array
double array[3][5] = {{3.0,5.0,2.0,1.0,0.0}, {4.0,8.0,6.0,3.0,3.0}, {7.0,6.0,2.0,3.0,5.0}};
//Computes the average value per row of array
for(i = 0; i < 3; i++){
printf("The average of row %d is %f\n", i, dAvg(array[i], 5));
}
return 0;
}