Sanket Lad
Sanket Lad

Reputation: 351

random or rand function prints the same value, even in different machines

I want to print a random number in the range 1 to 6. I have the following code.

printf("The random value is %d \n",random(6));

It is printing 1804289383 every time I run the code. Even on different machines. I also tried rand(6) still output is same. Even I removed 6, output does not change. Please suggest how to fix it

Thanks in Advance

Sanket

Upvotes: 3

Views: 4157

Answers (3)

Mihran Hovsepyan
Mihran Hovsepyan

Reputation: 11098

You shoud have srand() before rand() to generate new numbers each time. This code will show how do that:

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

int main()
{
    srand(time(0));
    printf("The random value is %d\n", 1 + rand() % 6);
    return 0;
}

Upvotes: 5

mu is too short
mu is too short

Reputation: 434665

First of all, random() does not take any arguments.

Secondly, from the fine manual:

Like rand(), random() shall produce by default a sequence of numbers that can be duplicated by calling srandom() with 1 as the seed.

So, unless you explicitly specify a seed by calling srandom(), random() will produce the same sequence of values every time.

Thirdly, random() returns a long so you should be using %ld in your printf() call.

Fourthly, learn about your compiler's warning flags, turn them all on, and pay attention to their output. You can turn off some of the warning flags once you understand why it is safe to do so.

Upvotes: 2

TML
TML

Reputation: 12966

The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value.

If no seed value is provided, the rand() function is automatically seeded with a value of 1.

So here's a quick example:

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

#define RSEED 2

int main (int argc, char *argv[]) {
  srand(RSEED);
  printf("The random value is %d\n", rand());
  return 0;
}

Upvotes: 1

Related Questions