关于C语言的随机函数

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

随机函数rand()

随机函数为rand(),括号内无需参数,可直接输出。
使用rand()产生随机数时,需加上头文件#include <stdlib.h>。rand()产生的随机数仅仅只是伪随机数,当程序定下后,无论执行多少次,产生的随机数顺序是不会发生变化的,要想使产生的随机数顺序发生变化需要引入随机种子。

随机种子srand(seed)

随机种子srand(seed)使用时,调用的头文件也是#include <stdlib.h>,其中seed为无符号整型,seed的值不同,产生的随机数顺序不同。一般来说为了使生成的数足够随机,采用的办法是使用时间作为随机种子,这里就要用到时间函数了。

时间函数time()

时间函数time()以s为单位,调用的头文件为#include <time.h>,每时每刻值都会发生变化,以时间函数作为随机种子的参数,进而使随机函数产生的随机数足够随机。

随机函数代码

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
	srand(time(NULL));//null需大写,小写不识别
	int magic;
	magic = rand() % 100 + 1;//产生1-100之间的随机数,先是对100取余得到0-99之间的随机数,然后加1,得到1-100之间的随机数
	prtintf("%d",magic);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44941350/article/details/89391069