Mogelijk duplicaat:
Genereer uniforme willekeurige getallen over het hele bereik
Ik wil het willekeurige getal in c++ genereren met in een bepaald bereik, laten we zeggen dat ik een getal tussen 25 en 63 wil hebben.
Hoe kan ik dat hebben.
Bedankt
Antwoord 1, autoriteit 100%
U kunt de willekeurige functionaliteit gebruiken die is opgenomen in de toevoegingen aan de standaardbibliotheek (TR1). Of je kunt dezelfde oude techniek gebruiken die werkt in gewone C:
25 + ( std::rand() % ( 63 - 25 + 1 ) )
Antwoord 2, autoriteit 90%
Aangezien nog niemand de moderne C++-aanpak heeft gepost,
#include <iostream>
#include <random>
int main()
{
std::random_device rd; // obtain a random number from hardware
std::mt19937 gen(rd()); // seed the generator
std::uniform_int_distribution<> distr(25, 63); // define the range
for(int n=0; n<40; ++n)
std::cout << distr(gen) << ' '; // generate numbers
}
Antwoord 3, autoriteit 63%
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);
}
Antwoord 4, autoriteit 58%
int range = max - min + 1;
int num = rand() % range + min;
Antwoord 5, autoriteit 24%
Gebruik de functie rand
:
http://www.cplusplus.com/reference/clibrary/cstdlib/rand /
Citaat:
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
Antwoord 6, autoriteit 8%
float RandomFloat(float min, float max)
{
float r = (float)rand() / (float)RAND_MAX;
return min + r * (max - min);
}