Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random Number: either 0 or 1

Tags:

c

random

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?

like image 525
g_rmz Avatar asked Feb 05 '14 14:02

g_rmz


People also ask

Is a single number either 0 or 1?

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.

What returns a random number between 0 and 1?

Here, we will use random() method which returns a random floating number between 0 and 1.

How do you generate a random number 0 or 1 C++?

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.


2 Answers

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.

like image 91
unwind Avatar answered Oct 26 '22 02:10

unwind


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.

like image 32
Hayri Uğur Koltuk Avatar answered Oct 26 '22 02:10

Hayri Uğur Koltuk