C++ 随机数,根据时间生成随机数,Srand 与Rand 产生随机数

C++中使用Rand()函数来产生“随机数”,实际上还要使用一个名为Srand()的函数产生种子,系统通过种子和随机数产生算法,生成不同的数字。当我们在使用Rand()没有调用Srand()时,系统会自动调用Srand(),种子相同时,产生的随机数相同。

为了能更好的产生随机数,我们通常使用系统时间作为随机数种子。

// srandTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>   //输入输出用到的头文件
#include <time.h>     //time 用到的头文件
#include <Windows.h>  //Sleep 用到的头文件
using namespace	std;

void testRand(void); //函数原型
void testSrand(void);//函数原型
int _tmain(int argc, _TCHAR* argv[])
{
	cout << "*************testRand**************" << endl;
	testRand();
	cout << "\r\n*************testSrand**************" << endl;
	testSrand();
	cin.get();//捕获输入种子后的ENTER键
	cin.get();
	return 0;
}
void testRand()
{
	int cinNum, coutNum;
	for (int i = 0; i < 5; ++i)
	{
		cout << "please enter a number as seed:" << endl;
		cin >> cinNum;
		srand(cinNum); //将输入的数字作为种子
		for (int i = 0; i < 5; ++i)
		{
			coutNum = rand() % 100; //产生1-100以内的随机数
			cout << "random number:" << coutNum << endl;
		}
	}
}
void testSrand()
{
	int coutNum;
	for (int i = 0; i < 5; ++i)
	{
		cout << "generate seed by system time" << endl;
		Sleep(1478); //设置程序休眠时长,若不设置,则由于计算机处理速度过快,系统时间相同,种子相同
		srand((unsigned)time(NULL));

		for (int i = 0; i < 5; ++i)
		{
			coutNum = rand() % 100;
			cout << "random number:" << coutNum << endl;
		}
	}
}
结果如下



  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值