Random Number Generator stuck at same values

In the code I am trying to create, I am using a random number generator to get two values between 1 and 999. However, in all the times I've run the program, the same sequence of numbers have been called each time. This is the only part of the code that uses the RNG. Any thoughts are welcome and appreciated. Thanks in advance.

1
2
  strstatnumber1 = rand() % 999 + 1;
  rngstatnumber2 = rand() % 999 + 1;
You'll need a seed - http://www.cplusplus.com/reference/cstdlib/srand/

#include <time.h> and put srand (time(NULL)); somewhere at the top of your program.
You need to seed the random the number generator.

A pseudo-random number generator, like std::rand, gets random numbers by starting with a number and performing a bunch of operations on it to create the next number, in a way that you can't predict the results. However, if you start with the same number, you'll always end up getting the same numbers afterwards, too. Hence, seeding the random number generator so that it starts with a different number each time.

For std::rand, the way to seed it is to use std::srand, and some data that changes every time you run the program (like, say, the current time):
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <cstdlib>
#include <ctime>

int main() {
    // use current time for seeding generator; 
    // only do this once in your program
    std::srand(std::time(0));

    std::cout << "Random number: " << (std::rand() % 999 + 1) << std::endl;
    return 0;
}

Keep in mind that std::rand is not a very good random number generator, particularly when using it in the way that you do. If you need numbers that are 'more random', try using the generators found in <random>: http://en.cppreference.com/w/cpp/numeric/random
Last edited on
Sweet! Thanks for all the help!
Topic archived. No new replies allowed.