Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Random numbers??

Status
Not open for further replies.

Naits

Programmer
Oct 10, 2001
90
NO
How to get a random number between 1 and 10?? I tried this:
a = 1+rand() %10;
Worked in dos mode, but not in Win 32. __________________
Visit my homepage
.: Game universE :.
 
Hi, one simple method I have used before is to use a while loop to increment or decrement the returned random number to within range:

int myRandNumber = rand(); // get the random number
int myRandRange = 10; // the limiting range
// if the number is greater than the limiting range
// reduce it by limits - eg. if returned number is 15
// it will become 5 when while loop stops
while (myRandNumber > 10)
myRandNumber -= myRandRange;
// if the number is less than the limiting range
// increase it by the range
while (myRandNumber < 1)
myRandNumber += myRandRange;

This is probably not the best way to do this but it works a treat!


 
You can use this:

(int)((upperbound - lowerbound + 1) * rand() + lowerbound)

if you want bitween 1 to 10:

(int)((10-1+1) * rand() +1)

so every number that you want biween 1 to something:

(int)(maxnumber * rand() +1)

Daniel Cohen Gindi
dcgsmix@gmx.net
 
You will need to seed the random function if you want different random numbers each time

srand(time(NULL));

Otherwise you will see the same random sequence (not so random)


Matt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top