查找所有周围细胞的平均值

时间:2017-03-08 05:08:07

标签: loops

给定一个矩阵[1 2 3; 4 5 6; 7 8 9; 10 11 12],我如何查看每个元素并找到它周围所有单元格的平均值?

1 个答案:

答案 0 :(得分:0)

你应该这样做。

// considering matrix[size][size] as input
int i,j,i_avg,j_avg;
int sum,count;
int average[size][size]; // the average array

for(i=0;i<size;i++)
{
    for(j=0;j<size;j++)
    {
        sum=0;
        count=0;
        for(i_avg=-1;i<=1;i++)
        {
            if(i+i_avg<0 || i+i_avg>=size)
                continue;
            for(j_avg=-1;j<=1;j++)
            {
                if(j+j_avg<0 || j+j_avg>=size)
                    continue;
                sum+=matrix[i+i_avg][j+j_avg];
                count++;
            }
        }
        average[i][j]=sum/count; // average of the surrounding elements of matrix[i][j]
    }
}