简体   繁体   中英

Adding random integer number in c++

如何在C ++中将100到-100之间的随机整数添加到int变量?

value += (rand() % 201) - 100; // it's 201 becouse with 200 the value would be in [-100, 99]

Don't forget to initialize the seed of random values (call srand()) or it will aways generate the same values. A good way to initialize the seed is with the time:

srand(time(NULL));
int rnd = 0;
rnd += ( ( rand() * 200 ) / RAND_MAX ) - 100;

Edit: Obviously this is going to have issues where RAND_MAX is equal to INT_MAX. In which case the answer below: Adding random integer number in c++ is probably more appropriate.

Edit: On Windows platforms RAND_MAX is defined 0x7fff and so this calculation will succeed. On other platforms this may not be the case.

You could do this:

Generate a Random number between 0 to 100 and subtract it with a random number between 0 to 100.

#include <cstdlib> 
#include <ctime> 
#include <iostream>

using namespace std;

int main() 
{ 
srand((unsigned)time(0)); 
int random_integer; 
random_integer = (rand()%101) - (rand()%101); 
cout << random_integer << endl; 
return 0;
}

In C++11:

#include <random>

int main()
{
    typedef std::mt19937_64 G;
    G g;
    typedef std::uniform_int_distribution<> D;
    D d(-100, 100);
    int x = 0;
    x += d(g);
}

Other sources of randomness are also available, eg:

minstd_rand0
minstd_rand
mt19937
ranlux24_base
ranlux48_base
ranlux24
ranlux48
knuth_b

Just change the typedef G to suit your taste. And you can seed g at construction time as you like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM