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

2019-01-09 18:49发布

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.

标签: c random
2条回答
Explosion°爆炸
2楼-- · 2019-01-09 19:24

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 ).

查看更多
在下西门庆
3楼-- · 2019-01-09 19:35

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;
}
查看更多
登录 后发表回答