C语言编程猜数字游戏 请大侠看看哪有问题

2024-12-29 14:34:28
推荐回答(2个)
回答1:

#include
#include
#include
#include
void main()
{
int answer[4],guess=0,times=0,a,b,i,j;
char c='Y';
srand(time(NULL)); /*注意这里*/
loop: if(c=='Y')
{
for(i=0;i<=3;i++)
{

answer[i]=rand()%10;
for(j=0;j{
while(answer[i]==answer[j])
answer[i]=rand()%10;
}
}

for(i=0;i<4;i++)
{
printf("%d ",answer[i]);
}
printf("\n");
printf("please guess:\n");
while(a!=4)
{
a=0;
b=0;
times++;

printf("%d guess:\n",times);

scanf("%d",&guess);
if(guess>999&&guess<10000)
{
for(i=3;i>=0;i--)
{

for(j=0;j<4;j++)
{
if((int)(guess/pow(10,i))==answer[j])
{
if(i+j==3)
a=a+1;
else
b=b+1;
}

}

guess=guess-(int)(guess/pow(10,i))*pow(10,i);
}
printf(" %d对%d位置不对\n",a,b);

}
else if(guess<1000||guess>9999)
{break;}

}}
if(a==4)
{
printf("congratulations!you are so clever\n");

printf("do you want to continue???(Y or N)");
scanf("%c",&c); /*注意这里*/
if(c=='Y')
{goto loop;}

}
}

回答2:

在scanf("%c",&c)之前,注意用fflush(stdin);来清空一下缓冲区,否则之前输入数字时最后按的回车键,会有ASCII码为10的字符留在缓冲区内,被scanf读走.

另外,在最后if(a==4)的代码中要加入a=0;不然下一次还没猜就会被判定成已经猜对了.

当然,times也要注意清0.