猜数字游戏
1、问题描述
程序每次执行都会随时间产生一个100以内的随机数,然后玩家来猜测这个数字,键入这个你猜测的数字给程序,程序会告诉你猜对了或者猜大了或者猜小了。
2、解决方案
首先利用C标准库的stdlib,中的srand()函数来产生一个随时间变化的随机数种子,然后利用rand()函数产生玩家要猜的这样一个随机数,然后利用循环让玩家猜,我们这里不限制猜测次数,让玩家猜对为止。
3、具体实现
void guessNum()
{
srand((unsigned)time(NULL)% 100 ) ; //产生随时间变化的随机数种子
int aimNum = rand() % 100; //产生玩家要猜的一个随机数
int userIn = 0;
while (1)
{
scanf("%d", &userIn);
if (userIn > aimNum)
printf("too big\n");//提示玩家猜大了
if (userIn < aimNum)
printf("too small\n");//提示玩家猜小了
if (userIn == aimNum)
{
printf("right, congratulations!\n");//提示猜对了
break;
}
}
}
4、测试
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void guessNum()
{
srand((unsigned)time(NULL)% 100 ) ;
int aimNum = rand() % 100;
//int aimNum = 98;
int userIn = 0;
while (1)
{
scanf("%d", &userIn);
if (userIn > aimNum)
printf("too big\n");
if (userIn < aimNum)
printf("too small\n");
if (userIn == aimNum)
{
printf("right, congratulations!\n");
break;
}
}
}
int main()
{
guessNum();
return 0;
}
结果: