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 好听的元旦简短祝福语