In this rather basic C++ code snippet involving random number generation:
include <iostream>
using namespace std;
int main() {
cout << (rand() % 100);
return 0;
}
Why am I always getting an output of 41? I'm trying to get it to output some random number between 0 and 100. Maybe I'm not understanding something about how the rand function works?
random functions like borland complier
You need to "seed" the generator. Check out this short video, it will clear things up.
https://www.thenewboston.com/videos.php?cat=16&video=17503
srand()
seeds the random number generator. Without a seed, the generator is unable to generate the numbers you are looking for. As long as one's need for random numbers is not security-critical (e.g. any sort of cryptography), common practice is to use the system time as a seed by using thetime()
function from the<ctime>
library as such:srand(time(0))
. This will seed the random number generator with the system time expressed as a Unix timestamp (i.e. the number of seconds since the date 1/1/1970). You can then userand()
to generate a pseudo-random number.Here is a quote from a duplicate question:
You need to change the seed.
the
srand
seeding thing is true also for ac
language code.See also: http://xkcd.com/221/
For what its worth you are also only generating numbers between 0 and 99 (inclusive). If you wanted to generate values between 0 and 100 you would need.
in addition to calling srand() as mentioned by others.
You are not seeding the number.
Use This:
You only need to seed it once though. Basically don't seed it every random number.