Generate random number between -99 and 99

Asked

Viewed 666 times

4

I’m having some difficulty here in my code which is the following, I know that to generate random numbers between 0 and 9 is - x = rand() % 10.

So now I wanted to generate numbers between -99 and 99, and I did so as follows - x = (rand()%200)-100, the problem is that in the negative numbers it generates the number -100, and in the positive only generates even the 99, as is intended.

How should I generate from the -99 and not of -100?

1 answer

6


Your problem is that the interval [0,200[ has 200 elements, but the range [-99,99] has only 199 elements. I suggest generating the range [0,199[ and then shift it negatively to [-99,100[:

x = (rand()%199)-99

For more details, see that answer to a similar question.

  • Oh yes I understood, now it worked. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.