c - 如何将这个 C 程序变成一个计算每行之和及其总和的函数?

标签 c function matrix

我的解决方案: 我在 CodeBlocks 中运行这个程序。它不工作,它显示:

       //error: array type has incomplete elements type 'int[]'
      //warning: return type of 'main' is not 'int'

我想计算每行的总和及其总和的函数。此解决方案不起作用,因为它在函数声明中显示错误。

   //function declaration
  void findSumEachRowAndTotalSum(int a[][], int c, int r){
     int i, j, rowSum, totalSum;
     //ask the user to give elements of rows
     for(i=0; i<c; i++){
       printf("\nGive elements of row %d:\n", i+1);
        for(j=0; j<r; j++)
        scanf("%d", &a[i][j]);
     }
   totalSum = 0;
   for(i=0; i<c; i++){
     rowSum = 0;
     for(j=0; j<r; j++){
     //calculates the sum of each row and total sums
      rowSum = rowSum + a[i][j];
      totalSum = totalSum + a[i][j];
   }
   //displays sum of each row on the screen
  printf("\nSum of row %d is %d", i+1, rowSum);
 }
  //displays the total sum of all rows on the screen
printf("\nTotal sum is %d\n", totalSum);
}

//main function
void main(void){
  int col, row, m[50][50], i, j;
  //...
  //function call
  findSumEachRowAndTotalSum(a,c,r);

}

最佳答案

错误是由于参数a定义到函数findSumEachRowAndTotalSum:

void findSumEachRowAndTotalSum(int a[][], int c, int r){

当多维数组作为函数的参数时,只允许第一维留空。必须指定所有其他人。

由于您似乎使用 cr 作为维度,您需要先给出这些参数,然后将它们用作数组的维度:

void findSumEachRowAndTotalSum(int c, int r, int a[c][r]){

然后你会像这样调用这个函数:

findSumEachRowAndTotalSum(50, 50, m);

关于警告,main函数必须定义为返回类型int,您需要随后返回一个值:

int main(void){
   ...
   return 0;    
}

关于c - 如何将这个 C 程序变成一个计算每行之和及其总和的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51971858/

相关文章:

jquery.addType()

c - 使用 Switch 语句的质数计数器(输出错误)?

c - 类型参数与我的程序中的其他参数不兼容

r - 如何使用outer()计算每个向量之间的中位数?

list - 将列表矩阵转换为正则矩阵

c - 转义序列\a 不起作用

c - 基于字符串参数的 WinDBG 条件断点

C 预处理器指令,这是正确的语法吗? #Ifdef foo ||酒吧

php - 编译php扩展时出现编译错误

函数指针与 Fn 特征对象