如何限制C ++中rand函数生成的数字

时间:2013-08-29 11:11:47

标签: c++ random

我希望有5个不同的随机数,但生成的位数相同。

我有这段代码:

int main()
{
  srand(time(0));
  unsigned int num1 = rand();
  cout << "random number 1 = " << num1 << endl;
  unsigned int num2 = rand();
  cout << "random number 2 = " << num2 << endl;
  unsigned int num3 = rand();
  cout << "random number 3 = " << num3 << endl;
  unsigned int num4 = rand();
  cout << "random number 4 = " << num4 << endl;
  unsigned int num5 = rand();
  cout << "random number 5 = " << num5 << endl;
}

输出结果为:

random number 1 = 278203697
random number 2 = 2102275865
random number 3 = 1018298572
random number 4 = 1658370388
random number 5 = 429634923

同时,我想要的输出是它为所有数字生成相同数量的数字。例如:

random number 1 = 278203697
random number 2 = 210227586
random number 3 = 101829857
random number 4 = 165837038
random number 5 = 429634923

如何使它像我想要的输出?

谢谢,感谢您的帮助

3 个答案:

答案 0 :(得分:4)

如果您希望所有数字都包含相同的数字位数,则您必须创建随机数的批次。或者使用C ++ 11中引入的一些new functionality,例如std::uniform_int_distribution类:

std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(100000000, 999999999);

for (int n = 1; n <= 5; ++n)
    std::cout << "random number " << n << " = " << dis(gen) << '\n';

您也可以设置输出的宽度,并用前导零填充它:

std::cout << std::setw(10) << std::setfill('0') << std::rand() << '\n';

答案 1 :(得分:-1)

您可以生成一个100000000到999999999(所有9位数字)范围内的随机整数,如下所示:

#include<cstdlib>

unsigned int num1 = rand()%900000000+100000000;

see also

cstdlib RAND_MAX在我的系统上是2147483647(Debian Squeeze g ++ 4.4)。

答案 2 :(得分:-2)

您所寻找的是100,000,000至999,999,999(含)范围内的数字,或等效地100,000,000加上介于0和899,999,999之间的数字:

unsigned int n = 100000000 + rand() % 900000000;

请注意usual caveats concerning modulo bias,如果它们对您的申请很重要。