C ++程序生成随机数
让我们看看如何使用C++生成随机数。在这里,我们正在生成一个范围为0到某个值的随机数。(在此程序中,最大值为100)。
为了执行此操作,我们使用srand()函数。这在C库中。函数voidsrand(unsignedintseed)植入函数rand使用的随机数生成器。
srand()的声明如下
void srand(unsigned int seed)
它带有一个称为种子的参数。这是一个整数值,伪随机数生成器算法将其用作种子。此函数不返回任何内容。
要获取数字,我们需要rand()方法。为了获得0到最大范围内的数字,我们使用了模运算符来获得余数。
对于种子值,我们将time函数结果提供给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
热门推荐
10 过年祝自己祝福语简短
11 拜年年祝福语大全简短
12 开业贺卡祝福语简短高级
13 新年祝福语创意简短霸气
14 住院送饭的祝福语简短
15 对好友的祝福语简短
16 晚安好梦祝福语简短
17 高考录取庆贺祝福语简短
18 祝福语简短唯美老师的话