用C语言求一个 3×3 矩阵主对角线元素之和
时间: 2023-11-30 09:04:55 浏览: 101
以下是一个用C语言求3×3矩阵主对角线元素之和的程序:
```c
#include <stdio.h>
int main() {
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int sum = 0;
for (int i = 0; i < 3; i++) {
sum += matrix[i][i];
}
printf("主对角线元素之和为:%d\n", sum);
return 0;
}
```
输出:
```
主对角线元素之和为:15
```
首先定义了一个3×3的矩阵,然后用循环遍历矩阵的主对角线元素,即行列下标相等的元素,将它们的值加起来得到主对角线元素之和。最后输出结果。
相关问题
c语言求一个3*3矩阵主对角线元素之和
以下是两种C语言求一个3*3矩阵主对角线元素之和的例子:
1.使用两个for循环遍历矩阵,当行数等于列数时,累加对角线元素的值。
```c
#include <stdio.h>
int main() {
int a[3][3], sum = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
scanf("%d", &a[i][j]);
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == j) {
sum += a[i][j];
}
}
}
printf("%d\n", sum);
return 0;
}
```
2.使用一个for循环遍历矩阵,当行数等于列数时,累加对角线元素的值。
```c
#include <stdio.h>
#define n 3
int main() {
int a[n][n], sum = 0;
printf("请输入矩阵(3*3):\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &a[i][j]);
}
}
for (int i = 0; i < n; i++) {
sum += a[i][i];
}
printf("对角线之和为:%d\n", sum);
return 0;
}
```
c语言求一个3x3矩阵主对角线元素之和。
以下是C语言求一个3x3矩阵主对角线元素之和的代码:
```c
#include <stdio.h>
int main() {
int matrix[3][3] = {{1,2, 3}, {4, 5, 6}, {7, 8, 9}};
int sum = 0;
for (int i = 0; i < 3; i++) {
sum += matrix[i][i];
}
printf("The sum of the main diagonal elements is: %d\n", sum);
return 0;
}
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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)