DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   C++ Random Numbers (http://www.daniweb.com/forums/thread1769.html)

AnthIste Oct 21st, 2007 8:54 am
Re: C++ Random Numbers
 
Quote:

and let's say i have a range from 2 to N, what should i do to get the output only from 2 to N and not 0 to N?because what's given in the previous thread is a function to choose from 0 to N.
thank you :D
Say you want a random number from 2 to n where n is 15, you would do the following:

int n = 15;
int random_int;

random_int = (rand()%n-2)+2;

lets look at the min/max scenarios.

MIN:
Should be 2 (right?)
so you random 0. But you said +2 at the end. so you get 2. which is minimum.

MAX:
should be 15. But max of (15-2) is 13. But you added 2. So its 15.

Problem solved


All times are GMT -4. The time now is 4:28 pm.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC