rand() issue in C programming?

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

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 */

You have to seed rand() .

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


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

链接地址: http://www.djcxy.com/p/68028.html

上一篇: Haskell中的并行monad映射? 像parMapM?

下一篇: 在C编程中的rand()问题?