Seeking help with random numbers

Started by
4 comments, last by greencrayon 17 years ago
Hi everyone. My math is way rusty, I hope someone can help me out. I am using rand() in c++ to generate random numbers for a game. I understand how to get a number between 1 and 100. But I am stuck when it comes to generating a number between say 20 and 40, or between the numbers stored in two variables. It would also be great if anyone could point me toward a math primer aimed at old farts who have forgotten everything they learned at school.
Advertisement
Generating a number between 20 and 40 is the same as generating a number between 0 and 20 and adding 20 to the result. In general, a number between numbers a and b can be generated by:
rand() % (b - a) + a
Look at your formula

Correct way should be
rand % (b - a) + b;
Quote:Original post by CrimsonSun
a number between numbers a and b can be generated by:
rand() % (b - a) + a

That way b-1 is the highest possible random number. I suggest
rand() % (b - a + 1) + a


Quote:Original post by Adam Hamilton
Correct way should be
rand % (b - a) + b;

No, because a is the lower number.
My brain was confused with some numbers, It's early in the morning. Thanks for pointing out my mistake :)
Thankyou for the responses guys, everything works just splendidly now.

This topic is closed to new replies.

Advertisement