编写函数 int sumBorder ( int a [ ROW ][ COL ])求二维数组周边一圈的元素之和。 ROW 和 COL 分别表示二维数组的行数和列数,用# define 定义好。
时间: 2024-06-03 21:09:24 浏览: 6
可以直接回答,代码如下:
#define ROW 5
#define COL 5
int sumBorder(int a[ROW][COL]) {
int sum = 0;
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
if (i == 0 || i == ROW - 1 || j == 0 || j == COL - 1) {
sum += a[i][j];
}
}
}
return sum;
}
请问还有什么需要帮忙的吗?我可以回答一些关于编程和技术的问题。
相关问题
用c语言编写函数:求出某二维数组周边元素之和
以下是用 C 语言编写的函数,可以计算二维数组周围元素之和:
```c
#include <stdio.h>
// 宏定义数组行列数
#define ROW 4
#define COL 4
// 计算周边元素之和
int sumSurrounding(int arr[ROW][COL], int row, int col) {
int sum = 0;
int i, j;
for (i = row - 1; i <= row + 1; i++) {
for (j = col - 1; j <= col + 1; j++) {
if (i >= 0 && i < ROW && j >= 0 && j < COL && (i != row || j != col)) {
sum += arr[i][j];
}
}
}
return sum;
}
int main() {
int arr[ROW][COL] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};
int row = 1, col = 2;
int sum = sumSurrounding(arr, row, col);
printf("sum = %d\n", sum);
return 0;
}
```
这个程序中,`sumSurrounding` 函数计算周围元素之和。它接收一个二维数组 `arr`、一个行索引 `row` 和一个列索引 `col`,返回周围元素之和。在函数内部,我们使用两个循环遍历 `arr` 周围的元素,并将它们的和累加到 `sum` 变量中。注意,我们使用 `if` 语句来确保我们只计算有效的周围元素。最后,我们在 `main` 函数中调用 `sumSurrounding` 函数,传入一个示例数组和一个行列索引,以计算周围元素之和。
C语言定义一个3*4的二维数组,编写自定义函数求数组周边所有元素之和
好的,我来编写这个自定义函数。首先,我们需要明确以下几点:
1. 3*4的二维数组共有12个元素,其中周边的元素有8个。
2. 周边的元素是指第一行、最后一行、第一列和最后一列上的所有元素。
根据以上条件,我们可以编写如下的函数:
```c
#include <stdio.h>
int sumAround(int arr[][4], int row, int col) {
int sum = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (i == 0 || i == row - 1 || j == 0 || j == col - 1) {
sum += arr[i][j];
}
}
}
return sum;
}
int main() {
int arr[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
};
int sum = sumAround(arr, 3, 4);
printf("%d\n", sum);
return 0;
}
```
在这个函数中,我们先定义了一个 `sumAround` 函数,用于计算二维数组周边所有元素之和。在这个函数中,我们使用了一个双重循环来遍历数组中的所有元素,然后判断当前元素是否处于周边位置(即第一行、最后一行、第一列和最后一列上的元素),如果是,就将这个元素的值累加到总和上。
在主函数中,我们定义了一个3*4的二维数组,并将其作为参数传递给 `sumAround` 函数。然后,我们将计算出的周边元素之和输出到控制台上。
希望这个自定义函数能够满足你的需求,如果有问题可以随时问我。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)