我正在尝试制定战舰计划。到目前为止,我的程序要求用户1输入他/她想要他们的船的位置。然后用户2猜测他们认为船在哪里。

如果用户2第一次没有击中玩家1的所有战舰,我会尝试让其重新提示用户2。

我尝试过在多个位置放置while循环while循环,但是每次我的程序崩溃时,那里的while循环现在也会使其崩溃。似乎没有任何作用。

#include <stdio.h>

int main(void)
{
    int board[2][2];
    int i, j;   //initialize loop variables
    int i2, j2; //initialize 2nd loop variables
    int i3, j3; // 3rd loop variables

    printf(" User 1: Enter a '1' where you want to place your ship and '0' where you do not.\n");

    /* these loops prompt the user to enter a 0 or 1 for each space in the 2d array depending on where they want their ship*/
    for(i = 0; i <= 1 ; i++)
    {
      for(j = 0 ; j <= 1 ; j++)
      {
          printf("space[%d][%d]: ", i, j);
          scanf("%d", &board[i][j]);
      }
    }

    while(board[i][j] == 1)
    {
        /*used to prompt the user2 as long as user1 still has ships left*/
        int board2[2][2];
        printf("User 2: Enter a '1' where you think User 1 placed their ship and '0' where \nyou do not.\n");

        /* Asks user2 for their guesses */
        for(i2 = 0 ; i2 <= 1 ; i2++)
        {
          for(j2 = 0 ; j2 <= 1 ; j2++)
          {
              printf("space[%d][%d]:", i2, j2);
              scanf("%d", &board2[i2][j2]);
          }
        }

        for(i3 = 0 ; i3 <= 1 ; i3++)
        {
            //compares user1 input to user2 guess
            for(j3 = 0 ; j3 <= 1 ; j3++)
            {
                if(board[i3][j3] == 1 && board2[i3][j3] == 1)
                {
                    printf("Hit!\n"); // if the inputs match display "hit"
                    board[i][j] = 0;
                }
                else
                {
                    printf("Miss!\n"); // if no hit display miss
                }
            }
        }
    }

    return 0;
}

最佳答案

我认为,根据战列舰计划的规则,我们为用户找到随机放置的舰船规定了一些限制。如果用户没有输入有效的响应,则您将继续重复此过程,直到输入了有效的响应或超过极限为止。

在您的情况下,您要重复此过程,直到user2找到没有任何限制的所有发货为止。

我在您的代码中发现了一些问题:


假设user1给出1 0 1 0,而user2给出1 1 1 1,则您的程序将获得成功的结果,因为您正在使用user2输入搜索完整的战板。
User2将连续运行,直到board [] []包含零值为止。


更改程序设计的几点-


保持用户2找到船的限制。
不要使用user2输入来搜索完整的矩阵,而是使用user2输入来检查战局的索引。


祝您好运迎接挑战。

关于c - 在C中的战舰程序中的while循环遇到麻烦,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41008466/

10-08 22:44