【发布时间】:2020-08-27 00:53:26
【问题描述】:
/*编写一个程序,使用函数计算方阵的对角线元素之和。这 函数应将总和返回给调用函数。 使用 gcc 版本 9.3.0 在 debain 测试中测试的程序 */
程序在不使用函数时运行良好,但存在问题,即传递的数组没有原始数组的所有元素,因此总和不正确。
#include <stdio.h>
#include <stdlib.h>
int sum(int a[10][10],int d);
int main(){
int r,c;
puts("Enter the dimension of square matrix");
scanf("%d %d",&r,&c);
if (r != c) {puts("Not a square matrix");exit(0);}//check if square matrix
int a[r][c];
puts("Enter the elements of the matrix");
for(int i=0; i<r; ++i){
for(int j=0; j<c; ++j){
printf("Enter a[%d][%d] element = ",i+1,j+1);
scanf("%d",&a[i][j]);
}
}
int result = sum(a,r);
printf("Sum of diagonal elements = %d \n",result);
return 0;
}
int sum(int a[10][10],int d){
//for a square matrix no of diagonal element = row/col of matrix
int result=0;
for(int i=0; i<d; ++i){
result=result+a[i][i];
}
return result;
}
【问题讨论】:
-
您需要为
r输入10并为c输入10才能有任何工作机会。 -
将 r 和 c 设为全局会是不好的做法,即添加 int r,c;上面 sum 的函数原型? (如果不是那么它将解决问题)
-
是的,这是不好的做法......而且它无论如何也解决不了你的问题。
标签: c