|
发表于 2023-12-8 21:08:00
|
显示全部楼层
问题出在第十行代码,我们可以知道,在一次内循环(你设置的第二次for循环)后,我们的x的值就已经和x2+g相等了,那么在进入第二次外循环时,再进入内循环时,系统判定x == x2+g+1(x大于x2+g了),那么就不再进入循环了,所以不会再继续打印,就导致程序运行时只有一行,并且y的值不在变化,(因为只有继续打印后面的行,才会显示出你想看到的y的变化,实际上,我们可以看到,y最后的值就是y2+k+1,这点你应该清楚)
改进代码:#include<stdio.h>
int main(){
int x,y,x2,y2,g,k,a=0;
int tu[100][100]={0};
scanf("%d %d %d %d",&x,&y,&g,&k);
x2=x;
y2=y;
for(y;y<=y2+k;y++){
printf("%d\n",y);
x = x2;//这里是唯一的修改。
for(x;x<=x2+g;x++){
tu[y][x]=a+1;
printf("x = %d,y =%d,tu=%d ",x,y,tu[y][x]);
}
}
return 0;
}
运行示例:5
5
5
5
5
x = 5,y =5,tu=1 x = 6,y =5,tu=1 x = 7,y =5,tu=1 x = 8,y =5,tu=1 x = 9,y =5,tu=1 x = 10,y =5,tu=1 6
x = 5,y =6,tu=1 x = 6,y =6,tu=1 x = 7,y =6,tu=1 x = 8,y =6,tu=1 x = 9,y =6,tu=1 x = 10,y =6,tu=1 7
x = 5,y =7,tu=1 x = 6,y =7,tu=1 x = 7,y =7,tu=1 x = 8,y =7,tu=1 x = 9,y =7,tu=1 x = 10,y =7,tu=1 8
x = 5,y =8,tu=1 x = 6,y =8,tu=1 x = 7,y =8,tu=1 x = 8,y =8,tu=1 x = 9,y =8,tu=1 x = 10,y =8,tu=1 9
x = 5,y =9,tu=1 x = 6,y =9,tu=1 x = 7,y =9,tu=1 x = 8,y =9,tu=1 x = 9,y =9,tu=1 x = 10,y =9,tu=1 10
x = 5,y =10,tu=1 x = 6,y =10,tu=1 x = 7,y =10,tu=1 x = 8,y =10,tu=1 x = 9,y =10,tu=1 x = 10,y =10,tu=1
我们会发现程序运行后打印的东西很不整洁,同时,原代码也不容易理解你的意图,可以有以下改进:#include<stdio.h>
int main(){
//定义loop_x和loop_y分别表示x和y循环自增的次数
int x,y,loop_x,loop_y,a=0;
//i和j用于循环过程的进行
int i,j;
int tu[100][100]={0};
//temp记录x的初始值
int temp;
scanf("%d %d %d %d",&x,&y,&loop_x,&loop_y);
temp = x;
for(i = 0;i <= loop_y;i ++,y ++){
x = temp;
for(j = 0;j <= loop_x;j ++,x ++){
tu[y][x]=a+1;
printf("x = %3d,y =%3d,tu=%3d ",x,y,tu[y][x]);
}
printf("————%d\n\n",y);//想让y的值出现在每行的后面应该放在内循环的下面
}
return 0;
}
运行示例:5
5
5
5
x = 5,y = 5,tu= 1 x = 6,y = 5,tu= 1 x = 7,y = 5,tu= 1 x = 8,y = 5,tu= 1 x = 9,y = 5,tu= 1 x = 10,y = 5,tu= 1 ————5
x = 5,y = 6,tu= 1 x = 6,y = 6,tu= 1 x = 7,y = 6,tu= 1 x = 8,y = 6,tu= 1 x = 9,y = 6,tu= 1 x = 10,y = 6,tu= 1 ————6
x = 5,y = 7,tu= 1 x = 6,y = 7,tu= 1 x = 7,y = 7,tu= 1 x = 8,y = 7,tu= 1 x = 9,y = 7,tu= 1 x = 10,y = 7,tu= 1 ————7
x = 5,y = 8,tu= 1 x = 6,y = 8,tu= 1 x = 7,y = 8,tu= 1 x = 8,y = 8,tu= 1 x = 9,y = 8,tu= 1 x = 10,y = 8,tu= 1 ————8
x = 5,y = 9,tu= 1 x = 6,y = 9,tu= 1 x = 7,y = 9,tu= 1 x = 8,y = 9,tu= 1 x = 9,y = 9,tu= 1 x = 10,y = 9,tu= 1 ————9
x = 5,y = 10,tu= 1 x = 6,y = 10,tu= 1 x = 7,y = 10,tu= 1 x = 8,y = 10,tu= 1 x = 9,y = 10,tu= 1 x = 10,y = 10,tu= 1 ————10
|
|