定义求和子函数求矩阵四周所有元素之和数组C语言
时间: 2024-06-14 16:03:45 浏览: 12
以下是定义求和子函数求矩阵四周所有元素之和数组C语言的示例代码:
```c
#include <stdio.h>
// 定义求和子函数
int sum(int arr[], int n) {
int s = 0;
for (int i = 0; i < n; i++) {
s += arr[i];
}
return s;
}
int main() {
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int sumArr[4] = {0}; // 初始化为0
// 求第一行和最后一行的和
for (int i = 0; i < 3; i++) {
sumArr[0] += matrix[0][i];
sumArr[2] += matrix[2][i];
}
// 求第一列和最后一列的和
for (int i = 0; i < 3; i++) {
sumArr[1] += matrix[i][0];
sumArr[3] += matrix[i][2];
}
// 输出结果
printf("四周元素之和分别为:");
for (int i = 0; i < 4; i++) {
printf("%d ", sumArr[i]);
}
return 0;
}
```
相关问题
定义求和子函数求矩阵四周所有元素之和数组
以下是求矩阵四周所有元素之和数组的Python代码:
```python
def calculateSurroundingSum(matrix):
row, col = len(matrix), len(matrix[0])
result = [0] * row
for i in range(row):
for j in range(col):
if i == 0 or i == row - 1 or j == 0 or j == col - 1:
result[i] += matrix[i][j]
return result
```
该函数接受一个二维数组 `matrix` 表示矩阵,返回一个一维数组 `result`,其中 `result[i]` 表示矩阵第 `i` 行四周所有元素之和。
函数首先获取矩阵的行数和列数,然后初始化一个长度为行数的数组 `result`,用于存储每一行四周所有元素之和。接着,函数使用两个嵌套的循环遍历矩阵的每一个元素,如果该元素位于矩阵的四周,则将其加入到对应行的 `result` 中。最后,函数返回 `result` 数组。
求矩阵各行元素之和C语言
以下是求矩阵各行元素之和的C语言代码:
```c
#include <stdio.h>
int main() {
int i, j, m, n, a[80][80], sum;
while (scanf("%d %d", &m, &n) != EOF) { // 多组测试数据
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &a[i][j]); // 读入矩阵
}
}
for (i = 0; i < m; i++) {
sum = 0; // 每行求和前要将sum清零
for (j = 0; j < n; j++) {
sum += a[i][j]; // 求和
}
printf("%d\n", sum); // 输出每行的和
}
}
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)