在C中的框架中输入二维数组
我试图让用户输入一个二维数组,然后它会以类似框架的方式打印出该数组,我编写了代码并且它可以工作,但是当涉及到打印数组时,程序只打印该数组的第一行用户一遍又一遍地输入这样的:
Enter size
3
Enter Array
1 2 3
4 5 6
7 8 9
Your Array:
a b c
# # # # #
1 # 1 2 3 #
2 # 1 2 3 #
3 # 1 2 3 #
# # # # #
这是我的代码: 我觉得它是一个小错误,但我就是找不到它。
#include <stdio.h>
int main(){
int i,j;
int y,x;
int n,a,num,readNum,z;
char ch;
ch = 'a';
num = 1;
printf("Enter size\n");
readNum = scanf("%d",&z);
int Board[z][z];
n = z+2;
a = n+1;
printf("Enter Array\n");
for(x=0;x<z;x++){
for(y=0;y<z;y++){
readNum = scanf("%d",&Board[x][y]);
}
}
printf("\nYour Array:\n");
x=0;
for(i=0;i<a;i++){
y=0;
for(j=0;j<a;j++){
if(((i==0)&&(j==1))||
((i==1)&&(j==0))||
((i==0)&&(j==n))||
((j==0)&&(i==n))){
printf(" ");
}
if ((i==0)&&(j==0)){
printf(" ");
}
if ((i==0 && (j>=2 && j<n))){
printf("%c ",ch);
ch++;
}
if ((j==0) &&(i>=2 && i<n)){
printf("%d ",num);
num++;
}
if(((i==1) && (j>=1 && j<=n))||
((i==n) && (j>=1 && j<=n))||
((j==1) && (i>1 && i<n ))||
((j==n) && (i>1 && i<n ))){
printf("# ");
}
if((i>1 && i<n) && (j>1 && j<n)){
printf("%d ",Board[x][y]);
y++;
}
}
printf("\n");
}
return 0;
}
I am trying to have the user input a 2d array and then it would print out that array in something like a frame, i wrote the code and it works but when it comes to printing the array the program just prints the first row of what the user inputted over and over like this:
Enter size
3
Enter Array
1 2 3
4 5 6
7 8 9
Your Array:
a b c
# # # # #
1 # 1 2 3 #
2 # 1 2 3 #
3 # 1 2 3 #
# # # # #
Here is my code: I feel its a small error but i just can't find it.
#include <stdio.h>
int main(){
int i,j;
int y,x;
int n,a,num,readNum,z;
char ch;
ch = 'a';
num = 1;
printf("Enter size\n");
readNum = scanf("%d",&z);
int Board[z][z];
n = z+2;
a = n+1;
printf("Enter Array\n");
for(x=0;x<z;x++){
for(y=0;y<z;y++){
readNum = scanf("%d",&Board[x][y]);
}
}
printf("\nYour Array:\n");
x=0;
for(i=0;i<a;i++){
y=0;
for(j=0;j<a;j++){
if(((i==0)&&(j==1))||
((i==1)&&(j==0))||
((i==0)&&(j==n))||
((j==0)&&(i==n))){
printf(" ");
}
if ((i==0)&&(j==0)){
printf(" ");
}
if ((i==0 && (j>=2 && j<n))){
printf("%c ",ch);
ch++;
}
if ((j==0) &&(i>=2 && i<n)){
printf("%d ",num);
num++;
}
if(((i==1) && (j>=1 && j<=n))||
((i==n) && (j>=1 && j<=n))||
((j==1) && (i>1 && i<n ))||
((j==n) && (i>1 && i<n ))){
printf("# ");
}
if((i>1 && i<n) && (j>1 && j<n)){
printf("%d ",Board[x][y]);
y++;
}
}
printf("\n");
}
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
之后。
当你从不改变
x
After
you never change
x
.当你完成一行时,你需要增加
x
。修复很小:
当您有
z
y
时,就该向下一行(增加 x)。以下代码是经过我修改后的代码,可打印正确的行(我最多尝试了 5 行):
You need to increment
x
when you finish a line.The fix is small:
When you had
z
y
s, it's time to go down one line (increment x).The following code, which is your code with my modification prints the correct lines (I tried up to 5):