Is there a function to generate a random int number in C? Or will I have to use a third party library?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
Hearing a good explanation of why using
rand()
to produce uniformly distributed random numbers in a given range is a bad idea, I decided to take a look at how skewed the output actually is. My test case was fair dice throwing. Here's the C code:and here's its output:
I don't know how uniform you need your random numbers to be, but the above appears uniform enough for most needs.
Edit: it would be a good idea to initialize the PRNG with something better than
time(NULL)
.STL doesn't exist for C. You have to call
rand
, or better yet,random
. These are declared in the standard library headerstdlib.h
.rand
is POSIX,random
is a BSD spec function.The difference between
rand
andrandom
is thatrandom
returns a much more usable 32-bit random number, andrand
typically returns a 16-bit number. The BSD manpages show that the lower bits ofrand
are cyclic and predictable, sorand
is potentially useless for small numbers.You want to use
rand()
. Note (VERY IMPORTANT): make sure to set the seed for the rand function. If you do not, your random numbers are not truly random. This is very, very, very important. Thankfully, you can usually use some combination of the system ticks timer and the date to get a good seed.C Program to generate random number between 9 and 50
In general we can generate a random number between lowerLimit and upperLimit-1
i.e lowerLimit is inclusive or say r ∈ [ lowerLimit, upperLimit )
rand()
is the most convenient way to generate random numbers.You may also catch random number from any online service like random.org.
On modern x86_64 CPUs you can use the hardware random number generator via
_rdrand64_step()
Example code: