gpt4 book ai didi

c - 未打印正确的字符数组 C

转载 作者:行者123 更新时间:2023-11-30 16:56:08 24 4
gpt4 key购买 nike

我正在尝试打印扫雷板。

目前,它只会打印 0 和炸弹位置,但不会打印相邻炸弹的数量。我认为这与我的牙套位置有关,但我不确定。

#include <stdio.h>
#include <stdlib.h>

int main() {
int width, tall, W;
int T=1;
int g;
int c=0;
printf("How wide do you want your board?\n Max 32 squares\n");
scanf("%d",&width);
printf("How tall do you want your board?\n Max 32 squares\n");
scanf("%d",&tall);
printf("How many mines do you want?\n Between 0 and 1000 please\n");
scanf("%d",&W);
int y= tall*width;
if (width>32 || width <=0 || tall>32 || tall <=0)
{
printf("Error, not valid dimensions\n");
T=0;
}
if (W>1000 || W<0 || W>(tall*width))
{
printf("Error, not a valid amount of mines\n");
T=0;
}
if (T==0)
{
printf("Sorry, you cannot play Mine sweeper!\n");
}
char array[tall][width];
int i,j;
if (T==1)
{
for(i=0;i<tall;i++)
{
for(j=0;j<width;j++)
{
g=rand() % y;
if (g<=W)
{
array[i][j]='*';
}
if(g>W)
{
array[i][j]='0';
}
}
}

for(i=0;i<tall;i++)
{
for(j=0;j<width;j++)
{
if(array[i][j]==0)
{
if(array[i-1][j-1]=='*')
{
c=c+1;
}
if(array[i][j-1]=='*')
{
c=c+1;
}
if (array[i+1][j-1]=='*')
{
c=c+1;
}
if (array[i-1][j]=='*')
{
c=c+1;
}
if (array[i+1][j]=='*')
{
c=c+1;
}
if (array[i-1][j+1]=='*')
{
c=c+1;
}
if (array[i][j+1]=='*')
{
c=c+1;
}
if (array[i+1][j+1]=='*')
{
c=c+1;
}
switch(c)
{
case 0:
{
array[i][j]=' ';
break;
}
case 1:
{
array[i][j]='1';
break;
}
case 2:
{
array[i][j]='2';
break;
}
case 3:
{
array[i][j]='3';
break;
}
case 4:
{
array[i][j]='4';
break;
}
case 5:
{
array[i][j]='5';
break;
}
case 6:
{
array[i][j]='6';
break;
}
case 7:
{
array[i][j]='7';
break;
}
case 8:
{
array[i][j]='8';
break;
}
}
}
}
}

for(i=0;i<tall;i++)
{
for(j=0;j<width;j++)
{
printf("%c",array[i][j]);
}
printf("\n");
}
}

return 0;
}

最佳答案

三个问题:
1.正如Barmar所说,您需要限制对阵列的访问。只需检查 if 子句中的 ij 是否为某个极值(0 或 tall-1width-1 )。
2. 您正在将 char 的值与

中的整数进行比较
if(array[i][j]==0)

在您的情况下,它总是评估为 false,因此您甚至没有输入代码的该部分。
3. 完成一个位置后,您不会将计数器 c 重置为 0

更正了该部分的代码

for(i=0;i<tall;i++){
for(j=0;j<width;j++){
c = 0;
if(array[i][j]=='0'){
if(i != 0 && j != 0 && array[i-1][j-1]=='*'){
c=c+1;
}
if(j != 0 && array[i][j-1]=='*'){
c=c+1;
}
if (i != tall-1 && j != 0 && array[i+1][j-1]=='*'){
c=c+1;
}
if (i != 0 && array[i-1][j]=='*'){
c=c+1;
}
if (i != tall-1 && array[i+1][j]=='*'){
c=c+1;
}
if (i != 0 && j != width-1 && array[i-1][j+1]=='*'){
c=c+1;
}
if (j != width-1 && array[i][j+1]=='*'){
c=c+1;
}
if (i != tall-1 && j != width-1 && array[i+1][j+1]=='*'){
c=c+1;
}
switch(c){
case 0:{
array[i][j]='0';
break;
}
case 1:{
array[i][j]='1';
break;
}
case 2:{
array[i][j]='2';
break;
}
case 3:{
array[i][j]='3';
break;
}
case 4:{
array[i][j]='4';
break;
}
case 5:{
array[i][j]='5';
break;
}
case 6:{
array[i][j]='6';
break;
}
case 7:{
array[i][j]='7';
break;
}
case 8:{
array[i][j]='8';
break;
}
}
}
}
}

关于c - 未打印正确的字符数组 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40050106/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com