Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does rand() always return the same value? [duplicate]

Tags:

c

random

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.

like image 508
Umut Avatar asked Mar 14 '12 22:03

Umut


People also ask

Is rand () truly random?

However, the numbers generated by the rand() are not random because it generates the same sequence each time the code executed.

What output would rand () generate?

rand() returns a pseudo-random number in the range of [0, RAND_MAX).

What is difference between rand () and Srand ()?

The rand() function in C++ is used to generate random numbers; it will generate the same number every time we run the program. In order to seed the rand() function, srand(unsigned int seed) is used. The srand() function sets the initial point for generating the pseudo-random numbers.

What does the rand function return in C?

The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX. RAND_MAX is a constant whose default value may vary between implementations but it is granted to be at least 32767.


2 Answers

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;
}
like image 127
MByD Avatar answered Sep 28 '22 12:09

MByD


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 ).

like image 21
Java42 Avatar answered Sep 28 '22 10:09

Java42