0
How do you get a random number between two numbers?
Hello, I would like to get a random number between two numbers a and b. I think to get that you have to use : a + (rand() % b) is it right? But the code doesn't work that well in my case... cout << 8 + (rand() % 16); often prints values over 16... Can you help me, tell me where I'm wrong? Thanks!! Here's the full code if you need it: https://code.sololearn.com/cyKaVVB38pkM/?ref=app
4 Answers
+ 4
It will generate out of range for sure. I will explain you why. For your example you want random number between 8-16(Including boundaries)
rand()%16 will generate any random number from 0-15 and you areadding 8 to it. So if rand()%16 generates number which is greater than 8 that would finally generate number grater than 16.(10+8).
Solution :
// including bounries
randomNumber = lowerLimit + (rand() %(higherLimit - lowerLimit+1));
//excluding boundries
randomNumber = (lowerLimit+1) + (rand()%(higherLimit-lowerLimit-1));
Note, if you use this formula make sure boundies are valid.means, higherLimit is always higher than lowerLimit.
Hope that helps. Thanks.
+ 5
use this logic
rand()%(max-min+1)+min
so in your code:
int Number = 8 + (rand() % (16-8+1));
+ 1
All right it works fine, thank you very much!
+ 1
Thank you, now I understand why that occured... I'll remember that, thanks for your help!