知识铺垫
生成随机数的方法:
调用rand函数、srand函数和time函数
以上函数的具体用法为:
随机数的生成方式
>rand函数生成随机数范围在0~32767之间
>在rand函数使用前需要调用srand函数设置随机数生成的基准值,可以用time函数的返回值做基准值
>在一次程序运行中,只需要设置一次基准值,后面可以生成多个随机数
>srand((unsigned int)time(NULL));
>生成a~b之间的随机数的方法:a + rand%(b-a+1)
int rand( void );
void srand( unsigned int seed );
time_t time( time_t *timer );//参数类型为指针,所以一下设置为NULL
组合起来生成随机数为:srand((unsigned int)time(NULL));
注意此处的强制类型转换,NULL为空指针
代码
#define _CRT_SECURE_NO_WARNINGS 1
#include<time.h>
#include<stdlib.h>
#include<stdio.h>
void game()
{
int ret = rand() % 100 + 1;
int guess = 0;
int count = 5;//限制次数
while (count)
{
printf("请猜数字:");
scanf("%d", &guess);
if (guess > ret)
printf("猜大了\n");
else if (guess < ret)
printf("猜小了\n");
else
{
printf("恭喜你,猜对了\n");
break;
}
count--;
}
if (count == 0)
printf("很遗憾,你失败了\n");
}
void menu()
{
printf("*********************\n");
printf("*** 0.exit 1.play***\n");
printf("*********************\n");
}
int main()
{
int input = 0;
srand((unsigned int)time(NULL));//在一次程序运行中只需要设置一次基准值,不能放在循环里
do
{
menu();
printf("请选择:");
scanf("%d", &input);
switch (input)
{
case 1:
game();
break;
case 0:
printf("退出游戏\n");
break;
default:
printf("请重新选择\n");
break;
}
} while (input);
return 0;
}

2万+





