求N*N的方阵两条对角线之和。N由键盘输入c语言
时间: 2024-05-11 21:13:56 浏览: 14
实现如下:
```c
#include <stdio.h>
int main() {
int n, i, j, sum1 = 0, sum2 = 0;
printf("请输入方阵的阶数:");
scanf("%d", &n);
int a[n][n];
printf("请输入方阵元素:\n");
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
scanf("%d", &a[i][j]);
if(i == j) {
sum1 += a[i][j]; // 主对角线元素之和
}
if(i + j == n - 1) {
sum2 += a[i][j]; // 副对角线元素之和
}
}
}
printf("主对角线元素之和:%d\n", sum1);
printf("副对角线元素之和:%d\n", sum2);
return 0;
}
```
运行结果示例:
```
请输入方阵的阶数:4
请输入方阵元素:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
主对角线元素之和:34
副对角线元素之和:32
```
相关问题
求N*N的方阵对角线之和。N由键盘输入c语言
实现如下:
#include <stdio.h>
int main() {
int n, i, j, sum = 0;
printf("请输入方阵的维度:");
scanf("%d", &n);
int matrix[n][n];
printf("请按行顺序输入矩阵元素:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
}
}
for (i = 0; i < n; i++) {
sum += matrix[i][i];
}
printf("对角线之和为:%d\n", sum);
return 0;
}
求n*n方阵数组对角线的和
好的,这是一个比较简单的问题,可以用以下代码实现:
```python
def diagonal_sum(matrix):
n = len(matrix)
sum = 0
for i in range(n):
sum += matrix[i][i]
return sum
```
其中,参数 matrix 是一个 n*n 的方阵数组,函数 diagonal_sum 求出该数组对角线的和并返回。具体实现方式是对从左上角到右下角的主对角线上的元素求和。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.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)