-1

I have following code:

#include <cstdlib>
#include <iostream>


using namespace std;

int main()
{
    cout << rand()%30<< endl;
    return 0;
}

I run this code and always get 11. Please explain why if you know. I use latest codeblocks and c++

qwertyu uytrewq
  • 299
  • 1
  • 4
  • 13

4 Answers4

13

The rand() function does not generate a truly random number; it actually returns the next pseudo-random value in a sequence of values ranging from 0 to RAND_MAX. You can change the starting point in that sequence using srand().

A common technique is to initialise srand() using the current time using the time() function, as shown below:

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

int main(int argc, char *argv[])
{
  srand(time(NULL));
  printf("%d", rand());
  return 0;
}

This causes the program to start generating numbers from a different point in the sequence every time it is run, making it appear to be less predictable.

Community
  • 1
  • 1
GoBusto
  • 4,632
  • 6
  • 28
  • 45
3

To initialize the random number generator, you need to call srand() with a seed.

You only need to initialize it once.

You will get the same sequence of numbers with the same seed, so normally, people use the current time as seed as that is pretty much guaranteed to change between program executions:

srand(time(0));
Community
  • 1
  • 1
nvoigt
  • 75,013
  • 26
  • 93
  • 142
1

rand() is an older random number generator, inherited from C. C++ has better RNG's available. Just use the std::default_random_engine if you don't want to worry about details.

Also, %30 reduces random-ness. You probably want a std::uniform_int_distribution<int>(0,30) there.

MSalters
  • 173,980
  • 10
  • 155
  • 350
0

In order to use the random number generator to get different number set in each time call it, you should definitely use with time.h. Include time.h below the then use like this;

srand(time(NULL));

printf("%d", rand());
Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103