简体   繁体   中英

Rand() not generating random variables in C

I've been trying to apply all advices found in this site but none seems to be working.

For the first part of the code I need to fill an array with random numbers (0 or 1) to simulate an epidemic spreading, but the array obtained is not the desired one at all... this is the code I wrote:

#include <stdio.h>
#include <stdlib.h>
#include <time.h> 

int main(int argc, char **argv)
{
    int N, BC, t, T, i, v[N];
    float b, g, p, r;

    /*Variable values initialization*/
    printf("Enter infection probability:\n");
    scanf("%f", &b);

    printf("Enter the number of individuals:\n");
    scanf("%d", &N);

    printf("Enter the number of time steps:\n");
    scanf("%d", &T);

    printf("Periodic boundary contitions? (Y:1 / N:0)\n");
    scanf("%d", &BC);   


    /*First set of individuals*/
    srand(time(NULL));
    for(i = 0; i < N; i++){ 
    v[i] = (rand()/RAND_MAX);
    }

    /*Check if array properly initialized*/
    printf("Initial array:\n" );
    for(i = 0; i < N; i++){
        printf("%d-", v[i]);
    }

The outcome I expected for the array was something like: 1-0-1-1-0-0-0-..., but I always get the following one:

Initial array: 0-0-2-15-0-0-0-0-0-0-

What am I doing wrong?

Thanks a million!

You should declare v[N] after

printf("Enter the number of individuals:\n");
scanf("%d", &N);

otherwise its size will be random since N isn't initialized when the memory allocated for v[] based on N is set.

If you want just 0 or 1 you should use a modulo:

srand(time(NULL));
for(i = 0; i < N; i++){ 
    v[i] = (rand() % 2);
}

all the even values generated by rand will become 0 and all the odd values will become 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM