**已关闭。**此问题需要debugging details。当前不接受答案。
编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
21小时前关门了。
Improve this question
我有一个问题,我打算写一个程序,采取一个矩阵/二维数组的元素,并平均它与周围的值。
例如,以下矩阵:
会变成:
4 4 5 6
6 6 7 8
8 9 10 10
值1与2、6、7求平均,结果等于4。
我的代码需要处理用户输入的任意大小的数组,这使它变得更加困难。
我是一个完全的C语言编码初学者,所以我将感谢任何帮助:)
我知道如何计算内部值(7,8)的平均值,因为它们周围有8个值,我的问题是编写代码来计算外部元素的平均值。
我创建的代码如下所示:
#include <stdio.h>
int main() {
int numRow, numCol, rows, cols;
// Collect the height from the user
printf("Enter image height: ");
scanf("%i", &numRow);
// Collect the width from the user
printf("Enter image width: ");
scanf("%i", &numCol);
// Create the input array
int nMatrix[numRow][numCol];
// Initialize the array with image data from user input
for (rows=0; rows<numRow; rows++){
printf("Enter pixel values for row %i (space separated): ", rows);
for(cols=0; cols<numCol; cols++){
scanf("%i", &nMatrix[rows][cols]);
}
}
printf("\nMatrix:\n");
for (rows = 0; rows<numRow; rows++){
for (cols = 0; cols<numCol; cols++){
printf("%i ",nMatrix[rows][cols]);
}
printf("\n");
}
// Create the output array */
int bMatrix[numRow][numCol];
// Perfrom the blurring algorithm
int sum = 0, count = 0;
for (rows = 0; rows < numRow; rows++){
for (cols=0; cols < numCol; cols++){
if (rows-1 >= 0 && cols-1 >= 0){
sum = sum + nMatrix[rows-1][cols-1];
count = count +1;
}
else if (rows-1>=0){
sum = sum + nMatrix[rows-1][cols];
count = count + 1;
}
else if (rows-1 >= 0 && cols + 1 <= numCol){
sum = sum + nMatrix[rows-1][cols+1];
count = count + 1;
}
else if (cols -1 >=0){
sum = sum + nMatrix[rows][cols-1];
count = count + 1;
}
else if (cols -1 >= 0 && rows -1 >= 0){
sum = sum + nMatrix[rows-1][cols-1];
count = count + 1;
}
else if (cols -1 >=0 && rows + 1 <= numRow){
sum = sum + nMatrix[rows+1][cols-1];
count = count + 1;
}
else if (cols + 1 <numCol && rows + 1 <= numRow){
sum = sum + nMatrix[rows+1][cols+1];
count = count + 1;
}
else if (cols + 1 <= numCol){
sum = sum + nMatrix[rows][cols+1];
count = count + 1;
}
else if (cols + 1 <= numCol && rows + 1 <= numRow && cols -1 >=0 && rows-1 >= 0){
bMatrix[rows][cols] = (nMatrix[rows][cols] + nMatrix[rows-1][cols-1] + nMatrix[rows+1][cols+1]+ nMatrix[rows-1][cols+1] +nMatrix[rows+1][cols-1] + nMatrix[rows+1][cols]+nMatrix[rows-1][cols]+nMatrix[rows][cols+1]+nMatrix[rows][cols-1])/9;
}
int avg = (sum / count);
bMatrix[rows][cols] = avg;
}
}
printf("\nBlurred Image\n");
for(rows = 0; rows < numRow; rows++){
for(cols = 0; cols < numCol; cols++){
printf("%i ", bMatrix[rows][cols]);
}
printf("\n");
}
// Display the blurred image data
return 0;
}
1条答案
按热度按时间cbjzeqam1#
为了避免VLA,我将使用1D数组而不是2D数组。您需要检查邻居是否不在数组的边界之外,将值相加并记住邻居的数量。您还需要使用“备用”矩阵,因为您不能覆盖原始矩阵(因为您需要知道原始值)
https://godbolt.org/z/54Tc79fdd