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

Recommended Answers

All 5 Replies

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

hope that helps.

thanks you maxmaxwell

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!

>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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.