srand函数随机产生一个数_1

简单举例:用系统时间做种子初始化。

代码如下:

#include <iostream>
#include <cstdlib>        /*用于srand();函数*/
#include <ctime>          /*用于time();函数*/
#include <windows.h>      /*用于 Sleep();函数*/

using namespace std;

int main()
{
	int seed;

	for (int i=0; i<100; ++i)
	{
		Sleep(1000);          /*延时1秒钟,如果不延时,则输出的数是一样的,这里是用系统时间做种子*/

		srand((unsigned)time(NULL));

		seed = rand() % 2 + 1;/*随机产生1或2赋给seed变量*/

		cout << seed << " ";
	}

	cout << endl;

	return 0;
}

你可能感兴趣的:(srand函数随机产生一个数_1)