[英]Average of a row in a two-dimensional array in C?
I am having trouble making a program that uses a function call to find the average of the rows in a two dimensional array? 我在制作一个使用函数调用来查找二维数组中行的平均值的程序时遇到麻烦吗? I can't get it to work in a larger program. 我无法在更大的程序中使用它。 I made this program to try and figure out what I am doing wrong, but to no avail. 我制作了这个程序,试图找出我做错了什么,但无济于事。 Any outside help would be greatly appreciated! 任何外部帮助将不胜感激! Here is the testing code: 这是测试代码:
#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;
}
}
When I run the program, it just says that the program has stopped working, on top of that, I don't feel confident that I will actually work once that first issue is solved. 当我运行该程序时,它只是说该程序已停止工作,最重要的是,我不确信一旦解决了第一个问题,我便会真正工作。 I am quite new to multi-dimensional arrays and especially so for passing them to functions. 我是多维数组的新手,尤其是对于将它们传递给函数而言。 Thanks again for any help! 再次感谢任何帮助!
Most errors were present in your dAvg
function: dAvg
函数中存在大多数错误:
Namely: 即:
r
was kept uninitialised therefore your indexing was not working 您的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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.