rand() issue in C programming? [duplicate]

2019-05-28 21:41发布

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;
}

5条回答
手持菜刀,她持情操
2楼-- · 2019-05-28 21:57

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!

查看更多
时光不老,我们不散
3楼-- · 2019-05-28 21:58

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

查看更多
劫难
4楼-- · 2019-05-28 22:01

You have to seed rand().

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

查看更多
该账号已被封号
5楼-- · 2019-05-28 22:02

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 */
查看更多
欢心
6楼-- · 2019-05-28 22:11

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