随机数C ++在一定范围内

可能重复:
在整个范围内均匀生成随机数

我想在C ++中生成某个范围内的随机数,可以说我希望数字在25到63之间。

我怎么有。

谢谢

Abdul Samad asked 2020-02-13T21:12:23Z
6个解决方案
187 votes

由于尚无人发布现代C ++方法,

#include <iostream>
#include <random>
int main()
{
    std::random_device rd; // obtain a random number from hardware
    std::mt19937 eng(rd()); // seed the generator
    std::uniform_int_distribution<> distr(25, 63); // define the range

    for(int n=0; n<40; ++n)
        std::cout << distr(eng) << ' '; // generate numbers
}
Cubbi answered 2020-02-13T21:13:01Z
17 votes

您可以使用标准库(TR1)新增内容中包含的随机功能。 或者,您可以使用与普通C语言相同的旧技术:

25 + ( std::rand() % ( 63 - 25 + 1 ) )
K-ballo answered 2020-02-13T21:12:41Z
17 votes
int random(int min, int max) //range : [min, max)
{
   static bool first = true;
   if (first) 
   {  
      srand( time(NULL) ); //seeding for the first time only!
      first = false;
   }
   return min + rand() % (( max + 1 ) - min);
}
Nawaz answered 2020-02-13T21:13:16Z
10 votes
int range = max - min + 1;
int num = rand() % range + min;
Benjamin Lindley answered 2020-02-13T21:13:32Z
5 votes
float RandomFloat(float min, float max)
{
    float r = (float)rand() / (float)RAND_MAX;
    return min + r * (max - min);
}
Yurii Hohan answered 2020-02-13T21:13:47Z
3 votes

使用rand函数:

[http://www.cplusplus.com/reference/clibrary/cstdlib/rand/]

引用:

A typical way to generate pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range:

( value % 100 ) is in the range 0 to 99
( value % 100 + 1 ) is in the range 1 to 100
( value % 30 + 1985 ) is in the range 1985 to 2014
Kiley Naro answered 2020-02-13T21:14:16Z
translate from https://stackoverflow.com:/questions/7560114/random-number-c-in-some-range