猜数字游戏C语言 帮我分析下

2024-12-28 17:13:42
推荐回答(2个)
回答1:

#include
#include
#include
int main()
{
int r,i=0,guess,count=0;

/*以当前系统时间作为随机数种子*/
srand((unsigned)time(NULL));

/*获取100以内的随机数[1, 100]*/
r=rand()%100+1; /*rand是一个函数需要加个()*/

printf("I have a number between 1 and 100.\n");
printf("please input your guess:\n");

/*循环去猜是哪个随机数*/
do
{
/*输入你想猜的随机数*/
scanf("%d",&guess);

/*计数器加1*/
count++;

/*如果所猜的数与随机产生的数不同,则提示高或低*/
if(guess>r)printf("Sorry!High!\n");
else
if(guesselse {
printf("Right,you win!\n");
break;
}

/*如果猜的次数大于7则你输了,如果你的机会用完了,还猜不出,可以将此值调大,然后重新编译此程序*/
if(count>7)
{
printf("I am win ang you fail!");
break; /*输了,程序就结束*/
}
printf("Please continue guess\n"); /*成功的话,你得继续完,除非你强制结束此游戏*/

}while(1);
printf("The random number is %d",r); /*最后向你的屏幕输出你猜不出的数字*/

return 0; /*输了,就可以正常返回了*/

}

/*下面是设置随机数种子及产生随机数的函数源代码,可以看一下,为什么要这么做,看不懂的话,上网查查吧*/
int rand( )
{
next = next

*
1103515245 + 12345;
return ((next >>16) & 32767);
}

void srand (Seed)
unsigned
int Seed;
{
next = Seed;
}

回答2:

#include
#include
#include
void main()
{
int r,i=0,guess,count=0;
srand((unsigned)time(NULL)); //随随机数初始化
r=rand()%100+1; // 产生1~100的随机数,注意要加括号
printf("I have a number between 1 and 100.\n");
printf("please input your guess:\n");
do
{
scanf("%d",&guess);
count++;
if(guess>r)printf("Sorry!High!\n");
else
if(guesselse {printf("Right,you win!\n");
break;
}
if(count>7)
{printf("I am win ang you fail!");
break;
}
printf("Please continue guess\n");

}while(1);
printf("The random number is %d\n",r);

}