Rand() not generating random variables in C

时间:2017-10-12 10:02:17

标签: c arrays random

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!

1 个答案:

答案 0 :(得分:0)

您应该在

之后声明v[N]
printf("Enter the number of individuals:\n");
scanf("%d", &N);

否则其大小将是随机的,因为在设置基于N的{​​{1}}分配的内存时,v[]未初始化。

如果您只想N0,则应使用模数:

1

srand(time(NULL)); for(i = 0; i < N; i++){ v[i] = (rand() % 2); } 生成的所有偶数值将变为rand,所有奇数值将变为0