【发布时间】: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