Generate random number between -99 and 99 [duplicate]

4

I'm having some difficulty here in my code which is as follows, 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 this way - x = (rand()%200)-100 , the problem is that in negative numbers it generates the number -100 , and in the positives it only generates itself to 99 , as is intended.

How do I generate from -99 and not -100 ?

    
asked by anonymous 16.10.2015 / 06:17

1 answer

5

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

x = (rand()%199)-99

For more details, see this response at a similar question .

    
16.10.2015 / 06:32