gpt4 book ai didi

c - C 中的格式化矩阵

转载 作者:行者123 更新时间:2023-11-30 17:57:42 25 4
gpt4 key购买 nike

我正在编写一个程序,它使用均值滤波器来平滑图像。现在我没有使用实际图像,只是使用整数,我的问题是我可以获得左角数字的平均值、左侧数字的平均值以及中间数字的平均值,但是当它输出结果时,它不会输出回矩阵。

例如。要求用户输入行和列的数字:输入是 5 和 5输出一个 5x5 矩阵

但是我会以从上到下的方式得到这些平均值的结果

  50
50
71
65
61
48 64 57
59 26 61
43 63 20

我想要实现的输出是

  50
71 48 64 57
65 59 26 61
61 43 63 20

显然这不是成品,因为我还没有对矩阵其余部分的平均值进行编程,但这个格式问题让我发疯。

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
// function that randomly generates numbers
void fillArray(int a[10][20], int m, int n)
{

int random;
int i,j;
for (i=0;i<m;i++)
{
for (j=0;j<n;j++)
{
random=rand()%100;
a[i][j]=random;
}
}
}

// function that prints the first matrix of random numbers
void printarray (int a[10][20], int m, int n)
{
int i,j;
for (i=0;i<m;i++)
{
for (j=0;j<n;j++)
{
printf("%4d", a[i][j]);
}
printf("\n");
}
}

// function that finds the mean for any number and its 4 nieghbors
void corner1 (int a[10][20], int n, int m)
{
int c[10][20];
int i,j;
for (i=0;i<m;i++)
{
for (j=0;j<n;j++)
{
if (i<=0 && j<=0)
{
c[i][j]=(a[i+1][j]+a[i][j+1])/2;
printf("%4d",c[i][j]);
}
}
}
printf("\n");
}



void middle(int a[10][20], int n, int m)
{
int c[10][20];
int i,j;
for (i=1;i<m-1;i++)
{
for (j=1;j<n-1;j++)
{
c[i][j]=(a[i-1][j]+a[i][j-1]+a[i+1][j]+a[i][j+1])/4;
printf("%4d",c[i][j]);
}
printf("\n");
}
}

void side1 (int a[10][20], int n, int m)
{
int c[10][20];
int i,j;
for (i=1;i<m;i++)
{
for (j=0;j<n-1;j++)
{
if (i<=1&&j>=0)
{
c[i][j]=(0+0+a[i-1][j]+a[i+1][j]+a[i][j+1])/3;
printf("%4d",c[i][j]);
printf("\n");
}
}
}
}

int main()
{
int a[10][20];

int m,n;
srand(time(NULL));

//User input
printf("please enter number of rows and columns\n");
scanf("%d %d", &m,&n);
fillArray(a,m,n);
printarray (a,m,n);
printf("The smoothed image is\n");
side1(a,m,n);
corner1(a,m,n);
middle (a,m,n);
getch();
return 0;
}

最佳答案

我可以想到两种解决方案:

  1. 将corner1、side1和middle存储在一个数组中。完成后打印数组(而不是内部corner1、side1和middle)。

  2. 迭代每一行。在该行上调用 side1,不打印换行符,在该行上调用 middle。由于需要进行大量调用(对于较大的图像),这会稍微降低效率,并且不会重用 printarray 代码,因此我建议您使用选项 1。

关于c - C 中的格式化矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12699309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com