c - c语言战舰程序中的while循环遇到问题

标签 c loops for-loop while-loop

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

如果用户 2 第一次没有击中玩家 1 的所有船只,我尝试让我的程序重新提示他们。

我尝试在几个地方放置一个 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 找到所有没有任何限制的船只。

我在您的代码中观察到一些问题:-

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

改变程序设计的一些要点-:

  1. 保留用户2找到船只的限制。
  2. 不要使用用户2输入搜索完整矩阵,而是使用用户2输入检查战斗板的索引。

祝挑战顺利。

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

相关文章:

java - 需要创建一个java程序,使用循环来检查密码是否正确。程序运行但输出不正确

c# - 遍历包含对象的字典

javascript - 循环遍历数组中的第一层并将其分配给变量

r - 使用 read.zoo 中的 Fun 更改日期格式

c - 未定义的引用使用automake

c - 在 while 循环中反转 printf 函数的输出

将 char 数组复制到 C 中的 char*

c - 在以太网帧中设置 CoS(PCP、802.1P)

c++ - 如何使用 Argv 编写基于范围的 For 循环?

c# - 只获取第一个项目与 SyndicateItem/foreach 的替代品