c语言 - 二维矩阵的值未分配权限



我是编程新手,我正在尝试编码以获得以下模式

如果n=3

3 3 3
3 1 3
3 2 3
3 3 3

如果n=4

4 4 4 4 4
4 4 1 4 4
4 4 2 4 4
4 4 3 4 4
4 4 4 4 4

如果n=5

5 5 5 5 5
5 5 1 5 5
5 5 2 5 5
5 5 3 5 5
5 5 4 5 5
5 5 5 5 5

等等。

我的上述模式的代码如下

#include<stdio.h>
int main() {
int n, row, col, mid, i, j, mat[50][50], midValue = 1;
printf("Enter the value of Nn");
scanf("%d",&n );
if(n % 2 == 0) {
row = col = n + 1;
}
else{
col = n;
row = n + 1;
}
mid = col / 2;
printf("%dn",mid );
for(i = 0; i < row; i++) {
for(j = 0; j < col; j++) {
if(j == mid && i != 0) {
mat[row][col] = midValue;
midValue++;
}
else {
mat[row][col] = n;
}
}
}
for(i = 0; i < row; i++) {
for(j = 0; j < col; j++) {
printf("%dt",mat[row][col]);
}
printf("n");
}
return 0;
}

但是,我所有的矩阵元素都只设置为 N 的值。我不知道我哪里做错了。谁能指出错误?

您正在设置和打印矩阵的唯一元素 -mat[row][col]

ij都不会用于设置值和打印值。

您需要更改:

mat[row][col] = midValue;

mat[i][j] = midValue;

mat[row][col] = n;

mat[i][j] = n;

printf("%dt",mat[row][col]);

printf("%dt",mat[i][j]);

最新更新