Random number of 0 and 1 in C

2

I need to generate a random number of 0's and 1's in C. Try to make two variables with random numbers, that of 0's and 1's, and the other so that it is the limit of a cycle that is executed to generate those 0's and 1's. I hope someone can help me. I leave part of the code to tell me if I'm wrong, lost or almost dead hahaha

int aleat = rand()%100+1;//aleat es el tope del ciclo 

for(int i = 0; i <aleat; i++){
    numero[i] = rand()%1+1; //0 o 1 generado que se guarda en un arreglo
}
    
asked by Alvarez Enrique 13.09.2017 в 01:51
source

1 answer

4

Your problem is that when wanting to take out the remainder of a random number between 1 always it comes out 0 because all number is divisible between one. That's why in the end numero[i] always takes the value of 0 + 1 .

To solve the problem you have to use % 2 , because the residuals of 2 are 0's and 1's.

In the end it would be something like this:

int aleat = rand() % 100 + 1;//aleat es el tope del ciclo

numero[aleat];

for(int i = 0; i < aleat; i++){
    numero[i] = rand() % 2; //0 o 1 generado que se guarda en un arreglo
}
    
answered by 13.09.2017 / 08:50
source