如何在C ++中生成一个随机数?
让我们看看如何使用C++生成随机数。在这里,我们正在生成一个范围为0到某个值的随机数。(在此程序中,最大值为100)。
为了执行此操作,我们正在使用该srand()方法。这在C库中。函数voidsrand(unsignedintseed)植入函数rand使用的随机数生成器。
的声明srand()如下-
void srand(unsigned int seed)
它带有一个称为种子的参数。这是要用作伪随机数生成器算法的种子的整数值。此函数不返回任何内容。
要获取数字,我们需要该rand()方法。为了获得0到最大范围内的数字,我们使用了模运算符来获得余数。
对于种子值,我们将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