免责声明 - 这是一些作业,所以我不想要答案,但没有人可以去获得一些指导(除非我想等一个星期,我通过信函学习)。
无论如何,我正在编写一个小扫雷功能。用户输入网格的大小和地雷的数量。然后我打印出电路板和结果。例如,在带有 2 个地雷的 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');
}