首先需要生成一个随机数,c语言中用srand((unsigned int)(time(NULL))产生一个不可预见的随机数序列,参考代码如下:
#include <stdio.h>
#include<time.h>
#include<windows.h>
void paint()
{
printf("***************************\n");
printf("*****1.play 2.exit*****\n");
printf("***************************\n");
}
void game()
{
int random_num = rand()%100+1; //产生1到100的随机数
int input=0;
printf("请输入数字>");
while(1)
{
scanf("%d",&input);
if(input>random_num)
printf("猜大了\n");
else if(input<random_num)
printf("猜小了\n");
else
{
printf("恭喜你猜对了\n");
break;
}
}
}
int main()
{
int num=0;
paint();
srand((unsigned)time(NULL));
while(1)
{
printf("请选择>");
scanf("%d",&num);
switch(num)
{
case 1:
game();
break;
case 2:
printf("退出游戏!\n");
return 0;
default:
printf("输入错误,");
break;
}
}
return 0;
}