1

I'm making a small "dungeons and dragons" type of program to help demonstrate rand() command to me. It's working just fine, except it always picks 2. Never 1. Help?

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    cout << "welcome to T's version of dungeons and dragons! \n Scenario:";
    int Scenario1 = rand() % 2 + 1;
    if(Scenario1==1){
        cout << "you come across a sleeping traveler, Do you ignore him, or steal his loot?";
    }
    else {
        cout << "you find an old bandit hideout in a cave. Do you ignore, or enter?";
    }

}
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
Trevader24135
  • 77
  • 1
  • 4
  • 9

2 Answers2

1

rand() will essentially generate the same series of numbers every time if you don't seed it.

The seed determines how the rand function generates numbers. For better 'randomness', call the following once at the beginning of the program, for example as the first statement inside main:

srand(time(NULL));

This seeds the random number generator with the value of the current UNIX timestamp, which should be unique enough to guarantee a better illusion of randomness.

More information on srand here:

http://www.cplusplus.com/reference/cstdlib/srand/

Edit

As others have mentioned, it's better to use the functionality found in the <random> header, as this is a more modern approach that avoids many of the pitfalls of the srand/rand paradigm.

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
Colin Basnett
  • 4,052
  • 2
  • 30
  • 49
0

rand() will always generate the number in same sequence.

To generate totally random number you can use srand(time(0)); time() is available in header file called #include <ctime>

Fore more detail please have a look :: https://www.youtube.com/watch?v=naXUIEAIt4U

Shravan40
  • 8,922
  • 6
  • 28
  • 48