C++ 随机数,根据时间生成随机数,Srand 与Rand 产生随机数
2016-08-17 11:28
495 查看
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; } } }结果如下
相关文章推荐
- C/C++中产生随机数(rand,srand用法)
- C++中用rand()和srand()产生随机数方法介绍
- C/C++中产生随机数(rand,srand用法)
- C/C++中产生随机数(rand,srand用法)
- C++中的srand(time(null))利用时间设置随机种子产生随机数
- C/C++中产生随机数(rand,srand用法)
- C/C++中产生随机数(rand,srand用法)
- C/C++中产生随机数(rand,srand用法)
- C/C++中产生随机数(rand,srand用法)
- C++中用rand()和srand()产生为随机数方法介绍
- C/C++中产生随机数(rand,srand用法)
- C++中用rand()和srand()产生随机数方法介绍
- [转]C/C++中产生随机数(rand,srand用法)
- C++利用srand和rand产生随机数
- C/C++随机数生成 rand() srand()
- C/C++中产生随机数(rand,srand用法)
- C++中的srand(time(null))利用时间设置随机种子产生随机数
- C/C++中产生随机数(rand,srand用法)
- C/C++中产生随机数(rand,srand用法)
- C/C++中产生随机数(rand,srand用法)