0412zc 发表于 2022-4-19 12:35:52

怎样改代码,才能让do-while正常运行?

这是一个井字棋游戏中的一个功能代码 function()。

下面的代码,我的需求是在不满足条件的时候,返回到do,重新运行。

请问各位大神,我这段代码哪里有问题,第二张图片和第三张图片的输出是一样的,只是换了一种方法写,第二章图片的内容看起来更直接。

多谢各位~

代码1:

void player_movement(){
    int n;
    mark='X';
    do{
      printf("please enter your move:\n");
      scanf("%d", &choice);

      if(choice==1 && board=='1')
            board=mark;
      else if(choice==2 && board=='2')
            board=mark;
      else if(choice==3 && board=='3')
            board=mark;
      else if(choice==4 && board=='4')
            board=mark;
      else if(choice==5 && board=='5')
            board=mark;
      else if(choice==6 && board=='6')
            board=mark;
      else if(choice==7 && board=='7')
            board=mark;
      else if(choice==8 && board=='8')
            board=mark;
      else if(choice==9 && board=='9')
            board=mark;
      else{
            n = 0;
            printf("Invalid move. This place is taken. Try Again please: \n");
      }
    }while(n = 0);
}

代码2:

void player_movement(){
   
    mark='X';
    int i,j,m,n;

    do{
      printf("please enter your move:\n");
      scanf("%d", &choice);
      for (i = 0; i < 3; i++)
      {
            for (j = 0; j < 3; j++)
            {   
                n = 3*i + j +1;
                m = (char)(n+48);
                if (choice != n)
                  continue;
                else if (choice == n && board == m){            // if (choice==1 && board=='1')
                  board=mark;                                           //   board=mark;
                  break;}                           
                else
                  printf("Invalid move. This place is taken. Try Again please: \n");
      }}
    }while(choice == n && board != m);
}

0412zc 发表于 2022-4-19 12:37:28

图片没了,补一下

hrpzcf 发表于 2022-4-19 12:48:32

while(n = 0)

while(n == 0)

zzxhh628 发表于 2022-4-19 13:03:11

看上楼,第一个代码里while里的应该n==0,在C/CPP中,=是赋值,==才是相等。

0412zc 发表于 2022-4-19 19:17:38

hrpzcf 发表于 2022-4-19 12:48
while(n = 0)

while(n == 0)

谢谢,我还发现,我应该在if之前,加上n=1, 否则n=0以后,每次循环n都是=0。

0412zc 发表于 2022-4-19 19:18:58

zzxhh628 发表于 2022-4-19 13:03
看上楼,第一个代码里while里的应该n==0,在C/CPP中,=是赋值,==才是相等。

谢谢,我还发现,我应该在if之前,加上n=1, 否则n=0以后,每次循环n都是=0。
我现在在研究第二段代码。理论上他们实现的功能是一样的。
页: [1]
查看完整版本: 怎样改代码,才能让do-while正常运行?