如何在C ++中的循环中生成不同的随机数?

让我们看看如何使用C ++生成不同的随机数。在这里,我们正在生成0到某个值范围内的随机数。(在此程序中,最大值为100)。

为了执行此操作,我们正在使用该srand()方法。这在C ++库中。函数void srand(unsigned int seed)植入函数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));
   for(int i = 0; i<10; i++) { //generate 10 random numbers
      cout << "The random number is: "<<rand()%max << endl;
   }
}

输出结果

The random number is: 6
The random number is: 82
The random number is: 51
The random number is: 46
The random number is: 97
The random number is: 60
The random number is: 20
The random number is: 2
The random number is: 55
The random number is: 91