Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same random numbers every time I run the program

Tags:

c++

random

My random numbers that output, output in the same sequence every time I run my game. Why is this happening?

I have

#include <cstdlib>  

and am using this to generate the random numbers

randomDiceRollComputer = 1 + rand() % 6; 
like image 794
soniccool Avatar asked Oct 13 '11 00:10

soniccool


People also ask

Why does Rand keep giving me the same number?

The RAND function in stand-alone applications generates the same numbers each time you run your application because the uniform random number generator that RAND uses is initialized to same state when the application is loaded.

Can you generate the same random numbers everytime?

random seed() example to generate the same random number every time. If you want to generate the same number every time, you need to pass the same seed value before calling any other random module function. Let's see how to set seed in Python pseudo-random number generator.

What happens if you use the random number multiple times in your program?

If you use randomNumber() multiple times in your program it will generate new random numbers every time. You can think of each randomNumber() like a new roll of a die.


2 Answers

You need to seed your random number generator:

Try putting this at the beginning of the program:

srand ( time(NULL) ); 

Note that you will need to #include <ctime>.

The idea here is to seed the RNG with a different number each time you launch the program. By using time as the seed, you get a different number each time you launch the program.

like image 151
Mysticial Avatar answered Sep 25 '22 05:09

Mysticial


You need to give the randum number generator a seed. This can be done by taking the current time, as this is hopefully some kind of random.

#include <cstdlib> #include <ctime> using namespace std;  int main() {     int  r;     srand(time(0));     r = rand();     return 0; }  
like image 40
tune2fs Avatar answered Sep 23 '22 05:09

tune2fs