Hey guys what I'm about to ask isn't for what I really need it for but learning how to use the rand() function in this manner will help me apply it to what I need it for.

Lets say I wanted to ask the user for a random integer such as 25. Now I want the computer to generate a random number between 0 and 25, I know that I can make a variable such as "int randNum = rand()" but that will give me a very large random number. How can I limit that random number the computer generates to 25?

Recommended Answers

All 5 Replies

rand() gives an integer between 0 and RAND_MAX.

To get a number between 0 and 25, I'd do something like the following:

1) Divide the output of rand() by RAND_MAX to get a number between 0 and 1.
2) Multiply the result by your desired maximum, in this case, 25.

i.e. -

randNum = (rand()/RAND_MAX)*25;

This code might need some tweaking. Play around with it a bit to get it doing what you want. (round, floor, etc, the result to get an integer)

What's RAND_MAX? is it something I can just call upon without it needing to be declared in the code or do I need to inlcude a special library?

RAND_MAX is defined in <stdlib.h>, which you have to include in your program to use rand() anyhow. So you don't have to include anything additional.

RAND_MAX is the largest number that can be output by rand(). You should check out your documentation for more detailed information.

Actually, to get a random number between 0 and 25 (exclusive) using rand(), use a modulus operation: num = rand() % 25

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.