0

So I am new to C++ and learning all alone... until now everything went fine, but i am learning how to use rand() and the result does bother me a little...

So my goal is to generate a random number for the HP of a player at the beginning of a game. To be fair, I set up a minimal HP of 50 points and I want to create a random number with 50 being the minimal and 200 the maximum.

int HP = 50 + rand() %200;

cout << HP;

Now, the problem is:

The program always give me the same int.
To check the result i created a new project and only displayed the rand() number with the same values, and I got the same result -> 91. this mean, I would say int HP = 91; would be exactly the same.

Practice and trial being the key to learn (I think) I tried the same rand() values on 5 new projects, always the same number...

walnut
  • 21,629
  • 4
  • 23
  • 59
Méli
  • 1
  • 2

2 Answers2

2

std::srand() seeds the pseudo-random number generator used by rand(). If rand() is used before any calls to srand(), rand() behaves as if it was seeded with srand(1).

Each time rand() is seeded with srand(), it must produce the same sequence of values on successive calls.

https://en.cppreference.com/w/cpp/numeric/random/rand

Therefore, what you're seeing is (awkardly) exactly what rand is supposed to do. The easy fix is to call std::srand(std::time(nullptr)); so that each time the program runs, it starts with a different seed.

The more advanced fix is to study The awesome C++ standard randum number library

std::default_random_engine e1(r());
std::uniform_int_distribution<int> uniform_dist(50, 250);
int HP = uniform_dist(e1);
Community
  • 1
  • 1
Mooing Duck
  • 64,318
  • 19
  • 100
  • 158
0

rand() isn't really the best random number generator, but if you're going to use it you need to seed it with the srand function as follows:

srand(time(0));

Community
  • 1
  • 1
jkb
  • 2,376
  • 1
  • 9
  • 12