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?
The RAND function in stand-alone applications generates the same numbers each time you run your application because the uniform random number generator that RAND uses is initialized to same state when the application is loaded.
Code. In the code below, the rand() function is used without seeding. Therefore, every time you press the run button, it generates the same number.
Description. RAND returns an evenly distributed random real number greater than or equal to 0 and less than 1. A new random real number is returned every time the worksheet is calculated.
Explanation : return type of rand() is integer.
You need to change the seed.
int main() { srand(time(NULL)); cout << (rand() % 101); return 0; }
the srand
seeding thing is true also for a c
language code.
See also: http://xkcd.com/221/
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With