rand with seed does not return random if function

2019-01-25 11:33发布

I wrote this C code below, when I loop, it returns a random number. How can I achieve the 5 different random values if myrand() is executed?

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

int myrand() {
    int ue_imsi;
    int seed = time(NULL);
    srand(seed);
    ue_imsi = rand();

    return ue_imsi;
}

int main()
{
    int value = 0;
    int i=0;
    for (i=0; i< 5; i++)
    {
        value =myrand();
        printf("value is %d\n", value);
    }
}

标签: c random
5条回答
贼婆χ
2楼-- · 2019-01-25 12:05

The point of seed() is to start the sequence of random numbers with a known value,
you will then always get the same sequence of numbers given the same seed.

This is why you have seed(), it both allows you to generate the same sequence for testing, or given a random seed (typically the time) you get a different sequence each time

查看更多
女痞
3楼-- · 2019-01-25 12:14

Seeding the generator should be done once(for each sequence of random numbers you want to generate of course!):

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

int main()
{
    int seed = time(NULL);
    srand(seed);
    int value = 0;
    int i=0;
    for (i=0; i< 5; i++)
    {
        value =rand();
        printf("value is %d\n", value);
    }
}
查看更多
Deceive 欺骗
4楼-- · 2019-01-25 12:15

Move the srand() call into main(), before the loop.

In other words, call srand() once and then call rand() repeatedly, without any further calls to srand():

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

int main()
{
    int value = 0;
    int i = 0;
    srand(time(NULL));
    for (i = 0; i < 5; i++)
    {
        value = rand();
        printf("value is %d\n", value);
    }
}
查看更多
Evening l夕情丶
5楼-- · 2019-01-25 12:17

If you want to reseed (for extra randomness) every time you call random(), here's one way you could do that:

srandom( time(0)+clock()+random() );
  • time() updates once per second, but will be different every time you run your program
  • clock() updates much more frequently, but starts at 0 every time you run your program
  • random() makes sure that you (usually) don't reseed with the same value twice in a row if your loop is faster than the granularity of clock()

Of course you could do more if you really, really, want randomness -- but this is a start.

查看更多
疯言疯语
6楼-- · 2019-01-25 12:18

Try this:

#include <stdio.h>
#include <time.h>
int main(void) {
    for (int i = 0; i < 10; i++) {
        printf("%ld\n", (long)time(NULL));
    }
}

My "guess" is that 10 equal values will be printed :)

查看更多
登录 后发表回答