Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a specific range of numbers from rand()?

Tags:

c

random

srand(time(null));  printf("%d", rand()); 

Gives a high-range random number (0-32000ish), but I only need about 0-63 or 0-127, though I'm not sure how to go about it. Any help?

like image 911
akway Avatar asked Jul 29 '09 20:07

akway


People also ask

What is the range of values generated by the rand () function?

The RAND function generates a random real number between 0 and 1.

What is the range of rand () in C?

The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX.

How do you give a range a rand in C++?

How to Generate Random Numbers in C++ Within a Range. Similar to 1 and 10, you can generate random numbers within any range using the modulus operator. For instance, to generate numbers between 1 and 100, you can write int random = 1+ (rand() % 100).


1 Answers

rand() % (max_number + 1 - minimum_number) + minimum_number 

So, for 0-65:

rand() % (65 + 1 - 0) + 0 

(obviously you can leave the 0 off, but it's there for completeness).

Note that this will bias the randomness slightly, but probably not anything to be concerned about if you're not doing something particularly sensitive.

like image 145
Tyler McHenry Avatar answered Sep 20 '22 10:09

Tyler McHenry