处理数组的函数,最后一个函数不是很懂,求解释解决思路
处理数组的函数,最后一个函数不是很懂,求解释
不知道注释上理解的有几个对的 ,还有就是这里说是用指针 但是除了声明上没见用其他的什么指针啊。
------解决方案--------------------
遍历是不是要对每个元素走一遍,然后tot += ar[r][c];
即:
- C/C++ code
# include <stdio.h> # define ROWS 3 # define COLS 4 void sum_rows(int ar[][COLS],int rows); void sum_cols(int [][COLS],int); int sum2d(int(*ar)[COLS],int rows); int main(void) { int junk[ROWS][COLS] = {{2,4,6,8},{3,5,7,9},{12,10,8,6}}; sum_rows(junk,ROWS); sum_cols(junk,ROWS); printf("Sum of all elemente = %d\n",sum2d(junk,ROWS)); return 0; } void sum_rows(int ar[][COLS],int rows) //这个函数不是使用遍历来对行进行求和 { int r; int c; int tot; for (r=0;r<rows;r++) { tot = 0; for (c=0;c<COLS;c++) tot += ar[r][c]; printf("row %d:sum = %d\n",r,tot); } } void sum_cols(int ar[][COLS],int rows) //这个也是使用遍历来对列进行求和 { int r; int c; int tot; for (c=0;c<COLS;c++) { tot = 0; for (r=0;r<rows;r++) tot += ar[r][c]; printf("col %d:sum = %d\n",c,tot); } } int sum2d(int ar[][COLS],int rows) //这个就不清楚了 我的理解是好像只是遍历了列,怎么会求出数组的总和呢。 { int r; int c; int tot = 0; for (r=0;r<rows;r++) for (c=0;c<COLS;c++) tot += ar[r][c]; return tot; }
不知道注释上理解的有几个对的 ,还有就是这里说是用指针 但是除了声明上没见用其他的什么指针啊。
------解决方案--------------------
遍历是不是要对每个元素走一遍,然后tot += ar[r][c];
即:
- C/C++ code
for (r=0;r<rows;r++) { for (c=0;c<COLS;c++) { tot += ar[r][c]; } }
------解决方案--------------------
注意tot变量,前两个函数都是在第一层for循环中重置为0了,最后一个是一直累加的