C++ Srand 与Rand 产生随机数
来源:互联网 发布:算法分析导论 英文版 编辑:程序博客网 时间:2024/05/16 12:11
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 namespacestd;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;}}}结果如下
1 0
- rand srand产生随机数
- c中的随机数产生rand和srand
- C语言产生随机数 srand rand
- linux c产生随机数rand(),srand()
- 利用srand,rand产生随机数-C语言
- 使用rand()与srand()产生随机数
- C++ Srand 与Rand 产生随机数
- C++,rand,srand随机数
- rand 和 srand产生随机数
- 1. srand rand 随机数产生
- rand 和 srand产生随机数
- srand (seed) rand() 产生随机数
- rand(),srand()产生随机数
- rand(),srand()产生随机数
- rand(),srand()产生随机数
- srand()和rand()产生随机数
- 随机数(rand与srand)
- C/C++中产生随机数(rand,srand用法)
- 获取view在屏幕中的位置
- leetcode 235. Lowest Common Ancestor of a Binary Search Tree
- C# 窗口、控件句柄操作
- Oracle索引(Index)创建使用
- Android 开发可能用到的SDK和库
- C++ Srand 与Rand 产生随机数
- Xcode插件管理工具Alcatraz,常用插件介绍 -iOS
- [leetcode] 341. Flatten Nested List Iterator
- Android 5.1.1 源码目录结构
- unity3D学习【功能实现】之十二:指定时间移动到目标位置
- 线程池中的实现
- 使用Zxing生成带有logo的二维码
- java泛型笔记
- 欢迎使用CSDN-markdown编辑器