9

Possible Duplicate:
Generating random numbers in C
using rand to generate a random numbers

I'm trying to generate random numbers but i'm constantly getting the number 41. What might be going so wrong in such a simple snippet?

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

int main(void)
{
    int a = rand();
    printf("%d",a);
    return 0;
}

Thanks for help.

Community
  • 1
  • 1
Umut
  • 409
  • 3
  • 7
  • 20

2 Answers2

23

You need to give a different seed, for example:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
    int a;
    srand ( time(NULL) );
    a = rand();
    printf("%d",a);
    return 0;
}
MByD
  • 135,866
  • 28
  • 264
  • 277
4

You need to seed the generator.

This is expected. The reason is for repeatability of results. Let's say your doing some testing using a random sequence and your tests fails after a particular amount of time or iterations. If you save the seed, you can repeat the test to duplicate/debug. Seed with the current time from epoch in milliseconds and you get randoms as you expect ( and save the seed if you think you need to repeat results ).

Java42
  • 7,628
  • 1
  • 32
  • 50
  • When i use (let's say:12) srand(12) before that the number changes but its still constant – Umut Mar 14 '12 at 22:16
  • @UmutŞenaltan: Seeding with the same value *will* create the same random sequence. See https://en.wikipedia.org/wiki/Pseudorandom_number_generator – Greg Hewgill Mar 14 '12 at 22:18
  • 1
    This is expected. The reason is for repeatability of results. Let's say your doing some testing using a random sequence and your tests fails after a particular amount of time or iterations. If you save the seed, you can repeat the test to duplicate/debug. Seed with the current time from epoch in milliseconds and you get randoms as you expect ( and save the seed if you think you need to repeat results ). – Java42 Mar 14 '12 at 22:21