我试图在 C 中对10 x 10二维数组内的值求和。让我们说例如在索引[0] [0]中我的值为1.我想将该元素和元素总结为其右边,左边,上边和下边。所以(1 + 0 + 1)= 3。
当我移动到索引[0] [1]时,我现在将添加4个值,因为我知道更长时间受到角落的限制。例如(0 + 1 + 0 + + 1)= 2。这是索引[0] [1]处的0值,并且给定顶部的右边,左边和底部的索引中的值超出其范围。我提供了一个图像打击来帮助说明我正在使用的内容。我尝试了很多东西,但我不确定如何用 C语言
在数学上做到这一点答案 0 :(得分:1)
这可以通过使用四个if
语句的简单函数来完成,以避免添加越界值:
#include <stdio.h>
#define BOARD_SZ 10
int sum_neighborhood(int, int, int [][BOARD_SZ], int, int);
int main(void)
{
int board[BOARD_SZ][BOARD_SZ] = { { 1, 0, 0, 1, 1, 1, 1, 1, 0, 1 },
{ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 1, 0, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 0, 1, 0, 1, 1, 1 },
{ 1, 0, 1, 1, 1, 0, 0, 0, 0, 1 },
{ 0, 1, 1, 1, 1, 1, 0, 1, 1, 0 },
{ 1, 1, 1, 1, 1, 1, 0, 0, 1, 1 },
{ 0, 1, 0, 0, 1, 0, 1, 0, 1, 0 },
{ 0, 1, 0, 0, 0, 1, 1, 0, 0, 1 },
{ 1, 1, 0, 1, 1, 0, 1, 0, 0, 0 } };
printf("Sum at [0][0] is %d\n",
sum_neighborhood(0, 0, board, BOARD_SZ, BOARD_SZ));
printf("Sum at [0][1] is %d\n",
sum_neighborhood(0, 1, board, BOARD_SZ, BOARD_SZ));
printf("Sum at [5][3] is %d\n",
sum_neighborhood(5, 3, board, BOARD_SZ, BOARD_SZ));
return 0;
}
int sum_neighborhood(int row, int col, int arr[][BOARD_SZ], int rows, int cols)
{
int sum = arr[row][col];
if (row - 1 >= 0) {
sum += arr[row-1][col];
}
if (row + 1 < rows) {
sum += arr[row+1][col];
}
if (col - 1 >= 0) {
sum += arr[row][col-1];
}
if (col + 1 < cols) {
sum += arr[row][col+1];
}
return sum;
}
节目输出:
Sum at [0][0] is 2
Sum at [0][1] is 2
Sum at [5][3] is 5
答案 1 :(得分:0)
int add(const int **arr, size_t nrows, size_t ncols)
{
int sum = 0;
for (size_t i = 0; i < nrows; ++i)
for (size_t j = 0; j < ncols; ++j)
sum += arr[i][j];
return sum;
}
使用一对嵌套循环来遍历行和列。
答案 2 :(得分:0)
一种简单的方法是仅考虑具有有效索引的值,但围绕给定索引i
,j
迭代整个方块。因此:
typedef struct {
int ** data; ///< data in row order
int rows, columns; ///< size of the data
} Array;
/// arr - pointer to the data
/// i, j - row and column to add values around
int sum(const Array * arr, int i, int j) {
int sumVal = 0;
for (int k = i-1; k <= i+1; k++)
for (int l = j-1; l < j+1; l++)
if (k >= 0 && k < arr->rows && l >= 0 && l < arr->columns)
sumVal += arr->data[k][l];
return sumVal;
}
然后,找到第一大块:
#include <limits.h>
typedef struct {
int sum, i, j;
} Sum_t;
Sum_t largest(const Array * arr) {
Sum_t max = {INT_MIN, 0, 0};
for (int i = 0; i < arr->rows; ++i)
for (int j = 0; j < arr->columns; ++j) {
int const s = sum(arr, i, j);
if (s > max.sum) {
max.sum = s;
max.i = i;
max.j = j;
}
}
return max;
}