Why does rand() always return the same value? [dup

2019-01-09 19:24发布

问题:

Possible Duplicate:
Generating random numbers in C
using rand to generate a random numbers

I'm trying to generate random numbers but i'm constantly getting the number 41. What might be going so wrong in such a simple snippet?

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

int main(void)
{
    int a = rand();
    printf("%d",a);
    return 0;
}

Thanks for help.

回答1:

You need to give a different seed, for example:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
    int a;
    srand ( time(NULL) );
    a = rand();
    printf("%d",a);
    return 0;
}


回答2:

You need to seed the generator.

This is expected. The reason is for repeatability of results. Let's say your doing some testing using a random sequence and your tests fails after a particular amount of time or iterations. If you save the seed, you can repeat the test to duplicate/debug. Seed with the current time from epoch in milliseconds and you get randoms as you expect ( and save the seed if you think you need to repeat results ).



标签: c random