- 1. rand() 伪随机数生成器
- 2. time() 返回系统时间
- 3. srand()
- 4. 总结
ANSI C提供了rand()生成随机数
#include2. time() 返回系统时间int rand(void); 功能: 返回一个伪随机数,区间在 0 到 RAND_MAX 之间 参数: 无 返回值: 0 到 RAND_MAX 随机数
#include3. srand()time_t time(time_t *tloc); 功能: 以秒为单位,返回一个表示时间的整数,起始时间是 1970-01-01 00:00:00 +0000 (UTC) 参数不为NULL,则表示时间的整数也会放在tloc指向的地址中。 参数: tloc 用来存储时间信息的变量的地址 (在调用之前,定义time_t变量,取地址传进来) 返回值: 成功 返回表示时间的整数,从1970-01-01 00:00:00 +0000 (UTC)开始计 失败 返回 -1 错误码 EFAULT tloc points outside your accessible address space (but see BUGS). tloc指针不可访问
#include4. 总结void srand(unsigned int seed); 功能: 将它的参数设置为rand()返回的伪随机整数序列的种子。若使用相同的种子值调用srand(),rand()的返回就是一样的。 参数: seed 种子,任何整数都可以 返回值 无
#include#include #include #include int main(){ int rand_num = 0; while(1){ //time_t 为 long 类型,这里需要强转一下类型 //time(0) 调用time函数,传值NULL(0) //将time(0)的返回值作为参数传给srand() srand((unsigned int )time(0)); //获取随机值 rand_num = rand(); printf("随机数 %d n", rand_num); sleep(1); } return 0; }



