rand() issue in C programming? [duplicate]

2019-05-28 21:48发布

问题:

Possible Duplicate:
Why do I always get the same sequence of random numbers with rand()?

So yeah, this might seem slightly noobish, but since I'm teaching myself C after becoming reasonable at Java, I've already run into some trouble. I'm trying to use the rand() function in C, but I can only call it once, and when it do, it ALWAYS generates the same random number, which is 41. I'm using Microsoft Visual C++ 2010 Express, and I already set it up so it would compile C code, but the only thing not working is this rand() function. I've tried including some generally used libraries, but nothing works. Here's the code:

#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "stdlib.h"

int main(void)
{
    printf("%d", rand()); //Always prints 41

    return 0;
}

回答1:

This because the rand() initializes its pseudo-random sequence always from the same point when the execution begins.

You have to input a really random seed before using rand() to obtain different values. This can be done through function srand that will shift the sequence according to the seed passed .

Try with:

srand(clock());   /* seconds since program start */
srand(time(NULL));   /* seconds since 1 Jan 1970 */


回答2:

You have to seed rand().

srand ( time(NULL) ); is usually used to initialise random seed. Otherwise,



回答3:

You need a seed before you call rand(). Try calling "srand (time (NULL))"



回答4:

You must first initialise the random seed using srand().

#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "stdlib.h"

int main(void)
{
    srand(time(NULL)); // Initialise the random seed.
    printf("%d", rand());
    return 0;
}


回答5:

rand() gives a random value but you need to seed it first. The problem is that if you execute your code more than once (probably), with the same seed srand(time(NULL)), then rand(); will give always the same value.

Then, the second option is to execute, as Thiruvalluvar says, srand(time(NULL)) and then rand().

The one above will give you 1000 random numbers. Try to execute this code and see what happens:

srand (time(NULL));
for (int i=0; i<1000; i++)
    {
    printf ("Random number: %d\n", rand());
    }

Hope it helps!