免责声明 - 这是一些功课,所以我不想要答案,但没有人去寻求指导(除非我要等一个星期,我通过函授学习。)
无论如何,我正在写一个小扫雷功能。用户输入网格的大小和地雷的数量。然后我打印出电路板和电路板。结果。例如,在有3个地雷的3 * 3电路板上,我会打印:
...
*..
..*
110
*11
10*
*显然是地雷。除了结果之外,一切都很顺利。我的比较似乎不起作用。我正在使用==符号比较字符,这看起来是完全合法的方法,但结果对我没有意义。
我不想要答案,只是朝着正确的方向前进。可能是因为我在我设置的原始数组的边界之外比较我的数组。如果是这种情况,那么我不知道如何解决这个问题。
我的代码如下。谢谢!
#include <stdio.h>
#include <stdlib.h>
void number1(int *stats);
void number2(int *stats);
int main(void)
{
int n,m,i,j,k,x, rand1, rand2, counter, numMines;
char choice;
do
{
printf("------------\n");
printf("lines (m) = : ");
scanf("%d", &m);
printf("\ncolumns (n) = : ");
scanf("%d", &n);
printf("\nMines = :");
scanf("%d", &numMines);
// check to ensure that numMines is not > n * m
if (numMines > m * n )
{
printf("Error. You cann't have more mines than available spaces ");
break;
}
counter = 0;
//create minefield array
char mineGrid[n][m];
//set all fields in minesweeper to safe (.)
for (j = 0; j < n; j++)
{
for (i = 0; i < m; i++)
{
mineGrid[j][i] = '.';
}
}
// Need to randomally make some mines for the array
//bounds of the random numbers is defined by the values of n and m
for (i = 0; i < numMines; i++)
{
//generate random number
rand1 = ((double)rand() / ((double)RAND_MAX + 1) * n);
rand2 = ((double)rand() / ((double)RAND_MAX + 1) * m);
//set as a mine:
mineGrid[rand1][rand2] = '*';
//Note : at the moment, mines can overlap. need to come back to fix this up.
}
//print out the msweeper grid
x = 0;
for (j = 0; j < n; j++)
{
printf("\n");
x++;
for (i = 0; i < m; i++)
{
printf("%c", mineGrid[j][i]);
}
printf(" ");
}
// here is where I will print the results:
printf("\n");
for (j = 0; j < n; j++)
{
for (k = 0; k < m; k++)
{
if (mineGrid[x+0][k+1]=='*')
counter++;
if (mineGrid[x+0][k-1]=='*')
counter++;
if (mineGrid[x+1][k+0]=='*')
counter++;
if (mineGrid[x+1][k-1]=='*')
counter++;
if(mineGrid[x+1][k+1]=='*')
counter++;
if (mineGrid[x-1][k+0]=='*')
counter++;
if (mineGrid[x-1][k-1]=='*')
counter++;
if(mineGrid[x-1][k+1]=='*')
counter++;
printf("%d", counter);
counter = 0;
}
printf("\n");
}
printf("\n\nTry again? (y/n:) ");
scanf("\n%s", &choice);
}while(choice == 'y' || choice == 'Y');
}
答案 0 :(得分:0)
正如0A0D所指出的那样,您使用x
来表示您要使用j
,但您也可以自由地从坐标中添加和减去1
,而不检查它们是否仍在场。那是在惹麻烦。