c语言中的rand()函数

c语言中的rand()函数

rand函数调用

  • rand()函数每次调用前都会查询是否调用过srand(seed),是否给seed设定了一个值,如果有那么它会自动调用srand(seed)一次来初始化它的起始值

  • 若之前没有调用srand(seed),那么系统会自动给seed赋初始值,即srand(1)自动调用它一次

srand函数

    srand函数是随机数发生器的初始化函数,原型:

void srand(unsigned int seed);

  • 这个函数需要提供一个种子,如srand(1),用1来初始化种子

  • rand()产生随机数时,如果用srand(seed)播下种子之后,一旦种子相同(下面的getpid方法),产生的随机数将是相同的。当然很多时候刻意让rand()产生的随机数随机化,用时间作种子 srand(time(NULL)),这样每次运行程序的时间肯定是不相同的,产生的随机数肯定就不一样了。


产生10个[10,30]的随机数

#include <stdio.h>
#include <stdlib.h>          //包含产生随机数的库函数
#include <time.h>
#include <iostream>
using namespace std;


void randa(int x[],int n,int a,int b) { //产生n个[a,b]的随机数
	int i;
	for (i = 0; i < n;i++) {
		x[i] = rand() % (b - a + 1) + a;
	}
}
void main() {
	int i, n = 10, x[10];
	int b = 30, a = 10;
	srand((unsigned)time(NULL)); //随机种子
	//产生随机数
	for (i = 0; i < n; i++) {
		randa(x, n, a, b);
	}
	//输出
	for (i = 0; i < n;i++) {
		cout<< x[i]<<" ";
	}
	cout << endl;
	system("pause");
	
}

输出:

28 27 14 21 23 21 19 22 30 14
请按任意键继续. . .

猜你喜欢

转载自blog.csdn.net/liu_hong_yan/article/details/109227395