C ++中的随机数生成
让我们看看如何使用C++生成随机数。在这里,我们正在生成一个范围为0到某个值的随机数。(在此程序中,最大值为100)。
为了执行此操作,我们正在使用该srand()方法。这在C库中。函数voidsrand(unsignedintseed)播种函数rand使用的随机数生成器。
的声明srand()如下:
void srand(unsigned int seed)
它带有一个称为seed的参数。这是一个整数值,伪随机数生成器算法将其用作种子。此函数不返回任何内容。
要获取数字,我们需要该rand()方法。为了获得0到max范围内的数字,我们使用了模运算符来获得余数。
对于种子值,我们将time函数结果提供给该srand()函数。
范例程式码
#include<iostream>
#include<cstdlib>
#include<ctime>
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
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志