我想在c ++中生成随机数,在某个范围内,假设我希望数字在25到63之间。
我怎么能拥有它。
由于
答案 0 :(得分:169)
由于尚未发布现代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
}
答案 1 :(得分:17)
您可以使用标准库(TR1)添加中包含的随机功能。或者你可以使用在普通C中运行的相同的旧技术:
25 + ( std::rand() % ( 63 - 25 + 1 ) )
答案 2 :(得分:17)
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);
}
答案 3 :(得分:9)
int range = max - min + 1;
int num = rand() % range + min;
答案 4 :(得分:3)
float RandomFloat(float min, float max)
{
float r = (float)rand() / (float)RAND_MAX;
return min + r * (max - min);
}
答案 5 :(得分:2)
使用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