0

I have int x

I would like to fill it with a randomly generated number between lets say 6 and 10

I know that x = 1 + rand() % maxRange; will limit the maximum range but i would also like to limit the minimum range.

How do i put a minRange on the rand() feature

any help would be great

Thanks

4
Contributors
5
Replies
7
Views
9 Years
Discussion Span
Last Post by joshua.tilson
0
int high=10;
int low=6;
rand () % (high - low + 1) + low;

hope that helps.

Edited by Dani: Fixed formatting

0

int high=10;
int low=6;
rand () % (high - low + 1) + low;

Hello,

I was hoping some one could shed some light on the reason this works. I have used rand() in the past to simulate rolling dice (1-100 etc.). I have never used the minimum number like this. why is it that rand() % 11 = a range of 6 - 10?

Thank you!

Edited by mike_2000_17: Fixed formatting

0

>I was hoping some one could shed some light on the reason this works.
Think of it as a normal range shifted to fit your lower bound. When you use x % y, it forces x to be within the range of 0 to y. This corresponds to rand() % ( high - low + 1 ) , or rand() % 5 . So now you have a number from 0 to 5 (excluding 5), but you really want a number from 6 to 11 (excluding 11). So you add the lowest number in your range, which is 6. This effectively shifts the range to what you want by changing the normal lower bound to the lower bound that you want.

0

Thank you Narue,

I knew you would come to my rescue. It makes much more sense to me now. I think i was just grappling with the unseen mathematics behind it.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.