猜数字游戏的规则是,电脑在0-9这10个数字中,任意不重复地选择四个排列成四位数,然后让玩的人猜使用的是哪四个/数字和数字在第几位;A代表数字对了但位置不对;B表示数字和位置都对了,A、B前的数字表示处于两种情况下的数字个数
example: 电脑给你猜的数字是2943,你猜2893,电脑就显示2A1B。
example: 电脑给你猜的数字是2943,你猜2893,电脑就显示2A1B。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void randnum(int array[4]);
int main()
{
int num_guess[4],num_user[4];
int guesstime=0,numA,numB,num_user_temp;
//生成随机数
randnum(num_guess);
back:scanf("%d",&num_user_temp);
//解析用户输入的数,放入数组中
if (num_user_temp>9999 || num_user_temp<0)
{
printf("error numbers,enter again!");
goto back;//大于四位数返回重输
}
num_user[0]=num_user_temp/1000;
num_user[1]=num_user_temp%1000/100;
num_user[2]=num_user_temp%100/10;
num_user[3]=num_user_temp%10;
//判断正确性
numA=numB=0;//将A,B清零
guesstime++;
for (int i=0;i<4;i++)
{
if (num_user[i]==num_guess[i])
{
numA++;
}
else
{
for (int m=0;m<4;m++)
{
if (num_guess[i]==num_user[m])
{
numB++;
break;
}
}
}
}
#ifdef _DEBUG
printf("%d%d%d%d/n",num_guess[0],num_guess[1],num_guess[2],num_guess[3]);
#endif
printf("%dA %dB/n",numA,numB);
if (numA!=4) goto back;
else printf("Successf! %d times in total",guesstime);
return 0;
}
#include <stdlib.h>
#include <time.h>
void randnum(int array[4]);
int main()
{
int num_guess[4],num_user[4];
int guesstime=0,numA,numB,num_user_temp;
//生成随机数
randnum(num_guess);
back:scanf("%d",&num_user_temp);
//解析用户输入的数,放入数组中
if (num_user_temp>9999 || num_user_temp<0)
{
printf("error numbers,enter again!");
goto back;//大于四位数返回重输
}
num_user[0]=num_user_temp/1000;
num_user[1]=num_user_temp%1000/100;
num_user[2]=num_user_temp%100/10;
num_user[3]=num_user_temp%10;
//判断正确性
numA=numB=0;//将A,B清零
guesstime++;
for (int i=0;i<4;i++)
{
if (num_user[i]==num_guess[i])
{
numA++;
}
else
{
for (int m=0;m<4;m++)
{
if (num_guess[i]==num_user[m])
{
numB++;
break;
}
}
}
}
#ifdef _DEBUG
printf("%d%d%d%d/n",num_guess[0],num_guess[1],num_guess[2],num_guess[3]);
#endif
printf("%dA %dB/n",numA,numB);
if (numA!=4) goto back;
else printf("Successf! %d times in total",guesstime);
return 0;
}
void randnum(int array[4])//生成不重复的四位随机数
{
srand(time(NULL));
for(int i=0;i<4;i++)
{
array[i]=rand()%10;
for(int m=0;m<i;m++)
{
if(array[i]==array[m]) {i--;break;}
}
}
}
{
srand(time(NULL));
for(int i=0;i<4;i++)
{
array[i]=rand()%10;
for(int m=0;m<i;m++)
{
if(array[i]==array[m]) {i--;break;}
}
}
}