程序代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct tag_Mark
{
int nNumMark;
int nPosMark;
int nMark;
};
tag_Mark GetCorrect(char *szOne, char *szTwo);
int main(int argc, char* argv[])
{
int nNumber = 0;
int nTemp = 0;
char cNumberArray[5] = {0};
char cTempArray[5] = {0};
char cTemp;
tag_Mark Mark;
srand( (unsigned)time( NULL ) ); //置随机数种子
while (nNumber < 1000 || nNumber > 9999)
{
nNumber = rand(); //随机取一个4位整数
}
itoa(nNumber, cNumberArray, 10); //转换成数组
while (1)
{
nTemp = 0;
while (nTemp < 1000 || nTemp > 9999)
{
//system("cls");
printf("请输入一个4位数:\r\n");
scanf("%d", &nTemp);
_flushall();
}
itoa(nTemp, cTempArray, 10);
Mark = GetCorrect(cTempArray, cNumberArray);
if (nTemp == nNumber)
{
printf("你太棒了,这个数字就是%d\r\n", nNumber);
printf("你一共猜了%d次\r\n", Mark.nMark);
system("pause");
return 0;
}
printf("%dA%dB\r\n", Mark.nPosMark, Mark.nNumMark);
if (Mark.nMark == 8)
{
printf("你已经猜了8次了,还要继续吗?(y/n)");
cTemp = getchar();
if (cTemp == 'Y' || cTemp == 'y')
{
}
else if(cTemp == 'n' || cTemp == 'N')
{
return 0;
}
}
if (Mark.nMark == 15)
{
printf("你已经猜了15次啦,是不是方法不对啊?休息一会再来玩吧!");
system("pause");
return 0;
}
}
return 0;
}
tag_Mark GetCorrect(char *szOne, char *szTwo)
{
static int nMark = 0;//记录猜测次数
int nNumMark = 0; //记录数字正确而位置不对的数的个数
int nPosMark = 0; //记录位置正确的数字个数
int i = 0, j = 0;
tag_Mark Mark;
for (i = 0; i < 4; i++)
{
if (szOne[i] == szTwo[i])
{
nPosMark++;
}
}
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
if (szOne[i] == szTwo[j])
{
nNumMark++;
break; //为了防止有重复,只记录第一个
}
}
}
nMark++; //查询次数加1
Mark.nNumMark = nNumMark;
Mark.nPosMark = nPosMark;
Mark.nMark = nMark;
return Mark;
}
闲着无聊帮你写了下.