C++ 程序生成随机数
接下来让我们来看看如何使用 C++ 生成随机数。此处我们在 0 到某个值(在此程序中,最大值为 100)的范围内生成一个随机数。
为执行此操作,我们使用 srand() 函数。此函数在 C 库中。函数 void srand(unsigned int seed) 为函数 rand 使用的随机数生成器设定种子。
srand() 的声明如下
void srand(unsigned int seed)
它采用一个称为 seed 的参数。这是一个整数值,用作伪随机数生成器算法的种子。此函数不返回值。
要获取数字,我们需要 rand() 方法。为了获取 0 到最大值范围内的数字,我们使用模运算符获取余数。
对于种子值,我们提供 time(0) 函数结果到 srand() 函数中。
示例代码
#include<iostream>
#include<cstdlib>
#include
using namespace std;
main() {
int max;
max = 100; //set the upper bound to generate the random number
srand(time(0));
cout << "The random number is: "<<rand()%max;
}输出 1
The random number is: 51
输出 2
The random number is: 29
输出 3
The random number is: 47
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP