I'm trying to generate a random int that is either 0 or 1 in C++. Right now, I receive a 0 every time I run this code, and I'm not sure why. What's the problem here?
#include <ctime> #include <cstdlib> srand(time(0)); int randomval = rand() % 2; cout << randomval << endl;
Until now I used the following code to generate a random bool : bool randomBool() { return 0 + (rand() % (1 - 0 + 1)) == 1; } // In main. cpp time_t seconds; time(&seconds); srand((unsigned int) seconds);
In order to generate Random boolean in Java, we use the nextBoolean() method of the java. util. Random class. This returns the next random boolean value from the random generator sequence.
The nextBoolean() method of the Random class is an instance method that generates pseudorandom, uniformly distributed Boolean values. True and false values are generated with approximately equal probability.
To get a boolean randomly, we can use the JavaScript Math. random() method. The random() method will generate a random float between 0 and 1. We can then put this in an if else condition statement.
I know this is an older question but I believe this answers the question properly.
Don't re-seed the the generator every time you run that code.
By seeding it to the same value every time, you're just gonna get the same "random" number. Remember this is a Pseudo-Random number generator, so based on the seed value, a "random" number will be generated. So if you seed it with the same number every time you're just gonna get the same number every time.
The solution is to call srand(time(NULL)) only once in your program execution. Then, each call to rand() will give you a different number every time.
It is called bad luck. Try it again.
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