再贴一个猜数字游戏。。。
#include <stdlib.h>#include <time.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
typedef struct {
char a;
char b;
} _resout;
void create_number(char *lp_num)
{
int i;
char num[4];
srand(time(NULL));
do {
for (i=0;i<4;i++)
num[i]=rand()%10;
} while ((num[0]==num[1])||(num[0]==num[2])||(num[0]==num[3])||
(num[1]==num[2])||(num[1]==num[3])||(num[2]==num[3]));
for (i=0;i<4;i++)
*(lp_num+i)=num[i];
}
_resout check_number(char *lp_num,char *lp_num_native)
{
int i,j;
_resout res={0,0};
for (i=0;i<4;i++) {
for (j=0;j<4;j++) {
if ( *(lp_num+i)==*(lp_num_native+j) ) {
if (i==j)
res.a++;
else
res.b++;
}
}
}
return res;
}
void input_number(char *lp_num) {
char buffer[80]; /*输入缓冲区防止用户输入的太多让程序挂掉*/
int i;
input_origin:
putchar( '?' );
gets( buffer );
if (strlen(buffer)!=4) goto input_origin;
if ((buffer[0]==buffer[1])||(buffer[0]==buffer[2])||
(buffer[0]==buffer[3])||(buffer[1]==buffer[2])||
(buffer[1]==buffer[3])||(buffer[2]==buffer[3]) ) goto input_origin;
for (i=0;i<4;i++) {
if (isdigit(buffer[i])==0) goto input_origin;
*(lp_num+i)=buffer[i]-'0';
}
}
int main() {
char num_native[4];
char num[4];
int i;
_resout res;
create_number(num_native);
for (i=0;i<10;i++) {
input_number(num);
res=check_number(num,num_native);
if (res.a==4) {
puts("yes!");
break;
}
printf("A%dB%d\n",res.a,res.b);
}
if (i==10) {
for (i=0;i<4;i++)
putchar('0'+num_native[i]);
}
putchar ('\n');
return 0;
}