2016-12-07 77 views
0

我想製作一個戰列艦程序。到目前爲止,我的程序要求用戶1輸入他/她想要他們的船隻的位置。然後用戶2猜測他們認爲船隻在哪裏。遇到麻煩在c中的戰列艦程序while循環

我試圖讓我的程序重新提示用戶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; 
} 
+0

'while(board [i] [j] == 1){':出入界限。我認爲無用的代碼。 – BLUEPIXY

+0

while(board [i] [j] == 1){:我同意這個部分現在是無用的,但我不知道在哪裏放置while循環來讓它重新提示用戶2。 – nicky

+0

User2只需要輸入預期的船的位置。並判斷它。 – BLUEPIXY

回答

0

我想,根據戰列艦計劃的規定,我們爲用戶指定了一些限制,以找到隨機放置的船隻。如果用戶沒有輸入有效的答覆,您將不斷重複此過程,直至輸入有效的答案或超出限制。

在你的情況下,你想重複這個過程,直到用戶2找到沒有任何限制的所有船隻。

我觀察你的代碼中的一些問題: -

  1. 假設用戶1給出了1 0 1 0和user2給予1 1 1 1,你的程序會給出成功的結果,因爲你與搜索完整的戰鬥板用戶2輸入。
  2. 用戶2將持續運行,直到board [] []包含零值。

一些點來改變你的程序的設計 - :

  1. 保持限制,對於user2找船。
  2. 不要用user2輸入搜索完整的矩陣,而是用user2輸入檢查你的戰鬥板的索引。

祝您好運。