954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

rand() range help

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

cl3m0ns
Light Poster
30 posts since Oct 2007
Reputation Points: 10
Solved Threads: 0
 
<code> 
int high=10;
int low=6;
rand () % (high - low + 1) + low;</code>


hope that helps.

maxmaxwell
Newbie Poster
16 posts since Nov 2007
Reputation Points: 10
Solved Threads: 1
 

thanks you maxmaxwell

cl3m0ns
Light Poster
30 posts since Oct 2007
Reputation Points: 10
Solved Threads: 0
 
<code> 
int high=10;
int low=6;
rand () % (high - low + 1) + low;</code>

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!

joshua.tilson
Light Poster
47 posts since Nov 2007
Reputation Points: 13
Solved Threads: 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.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

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.

joshua.tilson
Light Poster
47 posts since Nov 2007
Reputation Points: 13
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You