开发者

Adding random integer number in c++

How do开发者_StackOverflow中文版 I add in c++ a random integer number between 100 and -100 to an int variable?


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, e.g:

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜