I've this code:
srand(time(NULL));
int n = rand() % 1 + 0;
printf("%d\n", n);
But, if i put it (notsrand(time(NULL))
) in a loop for e.g., it generates only a sequence of 0.
There is another implementation for the random numbers between 0 and 1 or i've forgot something?
In mathematics and in computing systems, a binary digit, or bit, is the smallest unit of data. Each bit has a single value of either 1 or 0, which means it can't take on any other value. Computers can represent numbers using binary code in the form of digital 1s and 0s inside the central processing unit (CPU) and RAM.
Here, we will use random() method which returns a random floating number between 0 and 1.
C++ Random Number Between 0 And 1 We can use srand () and rand () function to generate random numbers between 0 and 1. Note that we have to cast the output of rand () function to the decimal value either float or double.
If you meant 0 or 1, your %
makes some sense, but you meant % 2
(or & 1
). Of course, the + 0
is still rather pointless, no idea what you're aiming for there. For an integer result of 0 or 1, just do:
const randomBit = rand() % 2;
The compiler will probably "strength-reduce" that to:
const randomBit = rand() & 1;
Also, make sure you only call srand()
once in your program or it won't have the effect you expect.
If you want either 0 or 1, just do
int n = rand() % 2
if what rand returns is even you'll get a 0, and if it's odd you'll get a 1 here.
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