【问题标题】:having trouble with while-loop in battleship program in cc语言战舰程序中的while循环有问题
【发布时间】:2016-12-07 02:32:56
【问题描述】:

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

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

我尝试在几个地方放置一个 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;
}

【问题讨论】:

  • while(board[i][j]==1){ :访问越界。我认为无用的代码。
  • while(board[i][j]==1){ :我同意该部分现在没用,但我不确定在哪里放置 while 循环以使其重新提示用户 2。
  • User2 只需要输入船的预期位置。并判断它。
  • 也许你应该先使用缩进让程序更容易理解。
  • 请重新格式化并添加一些注释来解释您希望每个部分做什么。重新定义重新提示用户 2 的条件。

标签: c loops for-loop while-loop


【解决方案1】:

我认为,根据战舰程序的规则,我们为用户指定了一些限制来找到随机放置的船。如果用户没有输入有效响应,您将不断重复此过程,直到输入有效响应或超出限制。

在您的情况下,您希望重复该过程,直到用户 2 找到所有船只,没有任何限制。

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

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

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

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

祝你挑战好运。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 2012-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多