用C语言写:编写函数求任意方阵每行、每列、对角线元素之和。
时间: 2024-03-01 12:55:21 浏览: 294
可以按照以下步骤来编写函数:
1. 定义一个函数,函数名为 `sum_matrix`,参数为一个二维数组 `matrix` 和一个整数 `n`,表示方阵的大小。
2. 定义三个变量 `sum_row`,`sum_col` 和 `sum_diag`,分别表示每行、每列和对角线的元素之和,初始化为 0。
3. 使用两个嵌套循环遍历二维数组 `matrix`,在循环中累加每行、每列和对角线的元素之和。
4. 返回一个包含三个元素的数组,分别表示每行、每列和对角线的元素之和。
以下是 C 代码实现:
```c
#include <stdio.h>
int* sum_matrix(int matrix[][100], int n) {
static int sums[3];
int sum_row, sum_col, sum_diag;
sum_row = sum_col = sum_diag = 0;
// 计算每行、每列和主对角线的元素之和
for (int i = 0; i < n; i++) {
sum_row = sum_col = sum_row + matrix[i][0];
sum_diag += matrix[i][i];
for (int j = 0; j < n; j++) {
sum_row += matrix[i][j];
sum_col += matrix[j][i];
}
}
// 将结果保存到数组并返回
sums[0] = sum_row / n;
sums[1] = sum_col / n;
sums[2] = sum_diag;
return sums;
}
int main() {
int n;
printf("请输入方阵的大小:");
scanf("%d", &n);
int matrix[100][100];
printf("请输入 %d x %d 的方阵:\n", n, n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
}
}
int* sums = sum_matrix(matrix, n);
printf("每行的元素之和: %d\n", sums[0]);
printf("每列的元素之和: %d\n", sums[1]);
printf("主对角线的元素之和: %d\n", sums[2]);
return 0;
}
```
注意,这里假设方阵大小不超过 100,因此二维数组的第二维大小定为 100。如果方阵大小可能小于 100,可以根据实际情况修改数组大小。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)