某个范围内的随机数 c++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7560114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:07:50  来源:igfitidea点击:

Random number c++ in some range

c++random

提问by Abdul Samad

Possible Duplicate:
Generate Random numbers uniformly over entire range

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

I want to generate the random number in c++ with in some range let say i want to have number between 25 and 63.

我想在 C++ 中生成某个范围内的随机数,比如说我想要 25 到 63 之间的数字。

How can i have that.

我怎么会有那个。

Thanks

谢谢

采纳答案by K-ballo

You can use the random functionality included within the additions to the standard library (TR1). Or you can use the same old technique that works in plain C:

您可以使用标准库 (TR1) 中添加的随机功能。或者您可以使用在普通 C 中工作的相同旧技术:

25 + ( std::rand() % ( 63 - 25 + 1 ) )

回答by Cubbi

Since nobody posted the modern C++ approach yet,

由于还没有人发布现代 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
}

回答by Nawaz

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);
}

回答by Benjamin Lindley

int range = max - min + 1;
int num = rand() % range + min;

回答by Yurii Hohan

float RandomFloat(float min, float max)
{
    float r = (float)rand() / (float)RAND_MAX;
    return min + r * (max - min);
}

回答by Kiley Naro

Use the randfunction:

使用rand函数:

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

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

Quote:

引用:

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