Loading

随机数


返回 我的技术栈(Technology Stack)



#include <time.h>
time_t time(time_t *t);
功能:获取当前系统时间
参数:常设置为NULL
返回值:当前系统时间, time_t 相当于long类型,单位为毫秒

#include <stdlib.h>
void srand(unsigned int seed);
功能:用来设置rand()产生随机数时的随机种子
参数:如果每次seed相等,rand()产生随机数相等
返回值:无

#include <stdlib.h>
int rand(void);
功能:返回一个随机数值
参数:无
返回值:随机数

举例应用:

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main()
{
	time_t tm = time(NULL);//得到系统时间
	srand((unsigned int)tm);//随机种子只需要设置一次即可
	//也可以直接写成: srand((unsigned int)time(NULL));

	int r = rand();
	printf("r = %d\n", r);

	return 0;
}

参考:
[1]C基础讲义2018修订版(黑马程序员)


posted @ 2021-07-19 10:30  言非  阅读(73)  评论(0编辑  收藏  举报