jeudi 4 octobre 2018

Why does rand() produce integers with difference of 3 or 4?

I read that rand() generates the same number when not seeded. So, I added srand() and i fed it with unity spaced integers.

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

int main()
{
    int i;

    for(i = 0 ; i < 10 ; i++)
    {
        srand(i);
        printf("%d ",rand());
    }
    return 0;
}

But the result was predictable.

38 41 45 48 51 54 58 61 64 68

The results had a difference of 3 or 4. I tried the same for the interval -9 to 0. The results were predictable again..!

9 12 15 19 22 25 28 32 35 38

Why is it that rand() generates such numbers..?

Why does srand(0) always lead to 38 and srand(1) always lead to 41 and so on..?




Aucun commentaire:

Enregistrer un commentaire