2

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;
}
Community
  • 1
  • 1
ZimZim
  • 3,291
  • 10
  • 49
  • 67
  • "For some reason"? No error messages? I find that... unlikely. When saying something(s) "doesn't work", try including what actually happens. In this case it's easy enough, but asking a complete question is just common sense and courtesy. – Dave Newton Apr 07 '12 at 16:31
  • I don't get an error message when using it once, but I do when I put it into a loop. That's why I said "For some reason". – ZimZim Apr 07 '12 at 16:34
  • Yeah. So include the error message? Just an idea. – Dave Newton Apr 07 '12 at 16:37
  • Lol, while you're here being critical (seriously no offense), everyone else has figured out the solution like 200 times. It appears to be a pretty common and solvable issue as the code is like 5 lines or so... – ZimZim Apr 07 '12 at 16:39
  • 1
    don't forget that real randomness does not exist; it's always pseudorandomness and generating the same pseudorandom sequence at each run **is a feature**. Likely, not useful in your case, though it is worth knowing it, I believe. – ShinTakezou Apr 07 '12 at 16:47
  • As I said, it's easy enough to solve (as is the other). But that isn't my point: "it doesn't work" is useless. When asking questions, provide the information you have. Your original question included the loop and associated commentary, so I assumed you actually cared about that part, and suggested that including information beyond "for some reason" would be appropriate. Because it would have been. – Dave Newton Apr 07 '12 at 16:53
  • Adding the "correction" to the example code is *very* confusing, and makes a nonsense of the question. To accept an answer is sufficient. – Clifford Apr 07 '12 at 16:55
  • @Clifford, alright, I didn't know that, I'm not really a stackoverflow veteran, I already removed it. – ZimZim Apr 07 '12 at 17:02
  • @ShinTakezou, thanks I'll take that into consideration. Every bit of information helps. – ZimZim Apr 07 '12 at 17:03
  • @DaveNewton, Ah, I think I misunderstood you. Yeah, since I didn't post the for loop itself I should have provided more information. I'll delete that for-loop part immediately, it turned out to be my own fault anyway (used to Java, declared a variable in the initialization space like for(int i = 0; i < 10; i++) – ZimZim Apr 07 '12 at 17:08
  • You did originally, and included expository text--recall that SO is async and ppl may respond while you're in the process of editing. I wasn't asking you to provide more information because anyone needed it to figure out eitherproblem, I was asking you to do it because it's common sense and courtesy to ask complete questions instead of relying on others to guess, follow up, try it themselves, etc. – Dave Newton Apr 07 '12 at 17:12
  • 1
    Be aware that the ability of `rand()` to generate a repeatable/deterministic sequence is intentional and sometimes useful. By either not calling `srand()` at all or calling it with a constant value, the sequence will be the same every time, and this is useful for testing/debugging, when you may not want the behaviour to be different on every test. – Clifford Apr 08 '12 at 09:51
  • 1
    If you call `time()` don't forget to `#include ` otherwise the compiler will assume a different prototype and invoke Undefined Behaviour. – pmg Apr 08 '12 at 11:23

5 Answers5

4

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 */
Francisco Presencia
  • 8,732
  • 6
  • 46
  • 90
Jack
  • 131,802
  • 30
  • 241
  • 343
3

You have to seed rand().

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

P.P
  • 117,907
  • 20
  • 175
  • 238
2

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

paulsm4
  • 114,292
  • 17
  • 138
  • 190
2

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;
}
Garee
  • 1,274
  • 1
  • 11
  • 15
1

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!

Francisco Presencia
  • 8,732
  • 6
  • 46
  • 90
  • The fist idea is a bad one. Constantly seeding the generator is both unnecessary and quite conceivably will result in a poor sequence. The second is in fact correct and will *not* produce the same random number every time. – Clifford Apr 07 '12 at 16:53
  • @Clifford Not only a poor sequence, but a predictable one. After the first 5 or 6 values come out you could technically find the seeding pattern, and predict the next 990 seeds/values. – Paul Apr 07 '12 at 17:14
  • Completely truth and sorry for the misunderstanding, I couldn't test it and just wrote from the top of my head. Now I tested it and corrected my answer but I cannot contribute much more than the former answers. – Francisco Presencia Apr 08 '12 at 11:13
  • Thank you @PaulP.R.O., I'll test my code properly next time – Francisco Presencia Apr 08 '12 at 19:21