您好,欢迎访问三七文档
#includeiostreamusingnamespacestd;constintMAXCOMMANDS=100,SIZE=79;//这里SIZE设最大值79,DOS一行能显示80个字符,中间间隔一个空格的'*',一行最多只能显示40个intturnRight(int);intturnLeft(int);voidgetCommands(int[][2]);voidmovePen(int,int[][SIZE],int,int);voidprintArray(constint[][SIZE]);intmain(){intfloor[SIZE][SIZE]={0};intcommand=0;intstaticdirection=0;//设为static,用来记住方向intcommandArray[MAXCOMMANDS][2]={0};//存贮1~6和9作为命令的数组intdistance=0;intcount=0;boolpenDown=false;getCommands(commandArray);command=commandArray[count][0];//即commandArray[0][0],第一个command//coutcommand:commandendl;while(command!=9){switch(command){case1:penDown=false;break;case2:penDown=true;break;case3:direction=turnRight(direction);break;case4:direction=turnLeft(direction);break;case5:distance=commandArray[count][1];movePen(penDown,floor,direction,distance);break;case6:cout\nThedrawingis:\n\n;printArray(floor);break;}command=commandArray[++count][0];//count自增,把存贮在数组commandArray里的命令全拿出来}return0;}voidgetCommands(intcommands[][2]){inttempCommand;inti;coutEntercommand(9toendinput):;cintempCommand;for(i=0;tempCommand!=9&&iMAXCOMMANDS;++i){commands[i][0]=tempCommand;if(tempCommand==5){cin.ignore();//忽略5后面的一个字符cincommands[i][1];//把移动距离存贮在commands[i][1]}coutEntercommand(9toendinput):;cintempCommand;//为了退出循环,这里只好输入9}commands[i][0]=9;//给之后的commands元素,赋值为9}intturnRight(intd){return++d3?0:d;}intturnLeft(intd){return--d0?3:d;}voidmovePen(intdown,inta[][SIZE],intdir,intdist){intstaticxPos=0,yPos=0;//设海龟在原点,intxTemp,yTemp;intj;//cout方向:dirdown=downendl;//测试用switch(dir){case0:xTemp=xPos;yTemp=yPos-1;for(j=1;j=dist*2&&(yTemp+j)SIZE;j+=2)//j+=2,平移时,隔开一个空格显示*号,这样看起来才像样{if(down){a[xTemp][yTemp+j]=1;}if(down==0)//当笔朝上时的移动{a[xTemp][yTemp+j]=0;}xPos=xTemp;//记住位置yPos=yTemp+j;//记住位置}break;case1:xTemp=xPos-1;yTemp=yPos;for(j=1;j=dist&&(xTemp+j)SIZE;++j){if(down){a[xTemp+j][yTemp]=1;//couta[xTemp+j][yTemp]\t;//测试用}if(down==0){a[xTemp+j][yTemp]=0;}xPos=xTemp+j;yPos=yTemp;}break;case2:xTemp=xPos;yTemp=yPos+1;for(j=1;j=dist*2&&(yTemp-j)=0;j+=2)//j+=2,平移时,隔开一个空格显示*号,这样看起来才像样{if(down){a[xTemp][yTemp-j]=1;}if(down==0){a[xTemp][yTemp-j]=0;}xPos=xTemp;yPos=yTemp-j;}break;case3:xTemp=xPos+1;yTemp=yPos;for(j=1;j=dist&&(xTemp-j)=0;++j){if(down){a[xTemp-j][yTemp]=1;}if(down==0){a[xTemp-j][yTemp]=0;}xPos=xTemp-j;yPos=yTemp;}break;}}voidprintArray(constinta[][SIZE]){intcount=0;for(inti=0;iSIZE;++i){for(intj=0;jSIZE;++j)cout(a[i][j]?'*':'');//a[i][j]不为0就是truecoutendl;}}
本文标题:c++ 海龟图习题
链接地址:https://www.777doc.com/doc-4194941 .html