猜数字game
#include<stdio.h>
#include<time.h>
#include<stdbool.h>
#define N 10
/*显示数组元素*/
void showArray(int num[],int count)
{
printf("数组元素为:");
int i;
for(i=0; i<count; i++)
{
printf("%d ",num[i]);
}
printf("/n");
}
/*生成m~n的一个随机整数*/
int randNum(int m,int n)
{
time_t t;
srand((unsigned)time(&t));
return rand()%(n-m+1)+m;
}
/*生成count个随机数,保存到数组中*/
void createRandNums(int randNums[],int count)
{
randNums[0] = randNum(1,9);
int i,j;
bool isRepeat = false;
for(i=1;i<count;i++)
{
do{
isRepeat = false;
randNums[i] = randNum(0,9);
for(j=0;j<i;j++)
{
if(randNums[i] == randNums[j])
{
isRepeat = true;//重复
break;
}
}
}while(isRepeat);
}
}
/*将一个整数分解到数组中*/
void spiltNum(int inputNum,int nums[],int count)
{
int index = count-1;
while(inputNum != 0)
{
nums[index] = inputNum%10;
inputNum = inputNum/10;
index--;
}
}
/*判断用户猜数的结果*/
void checkNums(int randNums[],int guessNums[],int count,int *a,int *b)
{
int i,j;
*a = 0;
*b = 0;
for(i=0;i<count;i++)
{
for(j=0;j<count;j++)
{
if(randNums[i] == guessNums[j] && i == j)
{
(*a)++;//数字和位置都正确
}else if(randNums[i] == guessNums[j])
{
(*b)++;
}
}
}
}
int main()
{
int randNums[N];//随机数组
int guessNums[N];//用户猜的数组
int n;//猜几位数
int inputNumber;//用户输入的数
int a = 0;//数字和位置都正确
int b = 0;
int i,j,k;
printf("请输入你要猜几位数:");
scanf("%d",&n);
printf("现在开始生成随机数,请稍等....../n");
createRandNums(randNums,n);
showArray(randNums,n);
do
{
printf("请输入一个%d位整数:",n);
scanf("%d",&inputNumber);
spiltNum(inputNumber,guessNums,n);//分解用户输入的整数
showArray(guessNums,n);
checkNums(randNums,guessNums,n,&a,&b);
printf("%dA%dB/n",a,b);
}while( a != n);
printf("猜对了!/n");
system("pause");
}