c - 海龟图形程序。为什么它不起作用?
问题描述
我正在尝试在这里做一个练习(第 246 页第 6.23 页)http://index-of.es/C++/C%20How%20to%20Program.pdf。我的代码打印了一个 12x12 的正方形,但我的代码打印了一个 25x25 的正方形,但左侧一半由 1 组成,另一半由 0 组成。为什么?
#include <stdio.h>
#include <stdlib.h>
#define SIZE 50
int main(){
int lifted=1, floor[50][50]={0}, commands[7]={1,2,3,4,5,6,9}, spaces, command, north=1, south=0, east=0, west=0, row=25, column=25, i, max=1;
while(command!=9){
printf("Enter a command: ");
scanf("%d",&command);
switch(command){
case 1:
lifted=1;
break;
case 2:
lifted=0;
break;
case 3:
if(north==1){
north=0;
east=1;
}else if(south==1){
south=0;
west=1;
}else if(west==1){
north=1;
west=0;
}else if(east==1){
south=1;
east=0;
}
break;
case 4:
if(north==1){
north=0;
west=1;
}else if(south==1){
south=0;
east=1;
}else if(west==1){
west=0;
south=1;
}else if(east==1){
north=1;
east=0;
}
break;
case 5:
printf("Enter a number of spaces: ");
scanf("%d",&spaces);
max=spaces;
break;
case 6:
for(i=0; i<50; i++){
for(int j=0; j<50; j++){
printf("%d ",floor[i][j]);
}
printf("\n");
}
break;
case 9:
exit(0);
}
if(lifted==0){
for(i=0; i<max; i++){
if(north==1){
row--;
}else if(south==1){
row++;
}else if(east==1){
column++;
}else if(west==1){
column--;
}
floor[row][column]=1;
}
}
}
return 0;
}
输出不绘制 12x12 正方形。为什么?请帮我。基本上我不知道该怎么办。有人能找出错误吗?我已经进行了一天多的练习。谢谢你。
解决方案
输出不打印 12x12 正方形,因为以下代码打印 50 行,每行 50 个数字。
for(i=0; i<50; i++){
for(int j=0; j<50; j++){
printf("%d ",floor[i][j]);
}
printf("\n");
}
您在原始问题中描述的明显损坏的输出的原因可能与此代码有关:
if(lifted==0){
for(i=0; i<max; i++){
if(north==1){
row--;
}else if(south==1){
row++;
}else if(east==1){
column++;
}else if(west==1){
column--;
}
floor[row][column]=1;
}
}
这是执行未经检查的数组访问,这可能导致未定义的行为,包括覆盖不应由此代码写入的内存片段。这可以解释各种奇怪的结果。为了防止这种情况发生,您需要添加四个检查,一个用于 50x50 网格的每个边缘。例如:
if(north==1){
if(--row < 0){
row = 0;
}
}else if(south==1) ...
推荐阅读
- android - 您可以在 android 中自定义 google maps 中的 ui 轮流导航活动吗?
- amazon-ec2 - 在 EC2-Fleet 上设置 Jenkins 环境变量的问题
- nfs - 使用 UBoot 从 NFS 服务器启动
- npm - 如何使用 forever.json 运行 npm 脚本?
- sql-server - 要选择的 Sql 条目
- docker - TestCafe docker - 对在主机 localhost 上运行的应用程序运行测试
- markdown - 将 Rmd 中的目录和从属关系列表分离为 PDF 文件
- sql - 如何从日期列中获取上个月的最后日期?
- python - 使用 BeautifulSoup 和不变的 URL 进行网页抓取
- c# - NSwag:如何在 C# -> Swagger -> C# 客户端中使用自定义值对象类型?