四、分支和循环(下)
1.rand函数
C语言提供了一个函数叫 rand,这函数是可以生成随机数的,函数原型如下所示:
int rand (void);
(void)
表示这个函数不需传参
表达以0x开头的16进制数字
rand函数的使用需要包含一个头文件是:stdlib.h
rand函数会返回一个伪随机数,这个随机数的范围是在0~RAND_MAX之间,这个RAND_MAX的大小是依赖编译器上实现的,但是大部分编译器上是32767。
产生5个随机数
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("%d\n", rand());
printf("%d\n", rand());
printf("%d\n", rand());
printf("%d\n", rand());
printf("%d\n", rand());
return 0;
}
运行两次后发现运行结果一致
rand函数是对一个叫“种子”的基准值进行运算生成的随机数。之所以前面每次运行程序产生的随机数序列是一样的,那是因为rand函数生成随机数的默认种子是1。
如果要生成不同的随机数,就要让种子是变化的。
2.srand函数
C语言中又提供了一个函数叫 srand,用来初始化随机数的生成器的,srand的原型如下:
void srand (1 unsigned int seed);
程序中在调用 rand 函数之前先调用 srand 函数,通过 srand 函数的参数seed来设置rand函数生成随机数的时候的种子,只要种子在变化,每次生成的随机数序列也就变化起来了。
那也就是说给srand的种子是如果是随机的,rand就能生成随机数;在生成随机数的时候又需要一个随机数,这就矛盾了。
3.time函数
在程序中我们一般是使用程序运行的时间作为种子的,因为时间时刻在发生变化的。在C语言中有一个函数叫 time ,就可以获得这个时间,time函数原型如下:
time_t time (time_t* timer);
time函数的时候需要包含头文件:time.h
time 函数会返回当前的日历时间,其实返回的是1970年1月1日0时0分0秒到现在程序运行时间之间的差值,单位是秒。返回的类型是time_t类型的,time_t 类型本质上其实就是32位或者64位的整型类型。
time函数的参数 timer 如果是非NULL的指针的话,函数也会将这个返回的差值放在timer指向的内存中带回去。
如果 timer 是NULL,就只返回这个时间的差值。time函数返回的这个时间差也被叫做:时间戳。
NULL为空指针,实际是0
int main()
{
srand((unsigned int)time(NULL));
printf("%d\n", rand());
printf("%d\n", rand());
printf("%d\n", rand());
printf("%d\n", rand());
printf("%d\n", rand());
return 0;
}
对于整个范围srand只需要设置一次
4.设置随机数的范围
如果要生成a~b的随机数,方法如下:
a + rand()%(b-a+1)
如果要生成100~200的随机数,方法如下:
100 + rand()%(200-100+1)
//余数的范围是0~100,加100后就是100~200
printf("%d",rand()%101+100);
游戏要求:
- 电脑自动生成1~100的随机数
- 玩家猜数字,猜数字的过程中,根据猜测数据的大小给出大了或小了的反馈,直到猜对,游戏结束
void menu()
{
printf("***********************\n");
printf("****** 1. play ******\n");
printf("****** 0. exit ******\n");
printf("***********************\n");
}
void game()
{
srand((unsigned int)time(NULL));
int guess = rand() % 101;
int count = 5;
int input = 0;
while (count)//计算剩余次数
{
count--;
printf("输入1-100猜测的数字");
scanf("%d", &input);
switch (input == guess)
{
case 1:
{
printf("游戏成功,正确数为%d\n",guess);
count = 0;//次数清零,退出循环
break;
}
case 0:
{
if (input > guess)
{
printf("猜大了\n");
}
else
{
printf("猜小了\n");
}
printf("你还剩下%d次机会\n",count);
break;
}
}
}
if (count == 0 && input != guess)//次数为0时进行最后一次猜对仍为游戏成功
{
printf("次数用尽,游戏结束,正确数字是%d\n", guess);
}
}
int main()
{
int input = 0;
do
{
menu();
printf("输入1以开始游戏,输入0以关闭游戏\n");
scanf("%d", &input);
switch (input)
{
case 1:
game();
break;
case 0:
printf("退出游戏");
break;
default:
printf("输入错误,请重新输入\n");
break;
}
}
while (input != 0);
return 0;
}
5.各进制
使用计算器计算
HEX: 16进制
DEC: 10进制
OCT: 8进制
BIN: 2进制
课件部分内容选自于比特就业课