Pregunta

For my current project i have created an event that should change depending on the random integer my code generates, the only problem is that i seem to always be getting the same path. In short i want it to be a 50% chance of either event occurring. Thanks, Simon

random1 = rand() % 1 + 0;
    if (random1 == 0) {
        int choice4;
        cout << "Your character screams at the top of his lungs, " << endl;
        cout << "this causes the dragon to immediately to bow in fear..." << endl;
        cout << "It turns out dragons are very sensitive to hearing....." << endl;
        system("pause");
        cout << "\nIt seems the dragon is requesting you ride it!\n" << endl;
        cout << "Will you ride it?\n" << endl;
        cout << "1. Ride it" << endl;
        cout << "2. Or Wait here." << endl;

        cin >> choice4;
        cin.ignore();
        system("cls");

        if (choice4 == 1){
            Ending();
        }
    }
    else if (random1 == 1) {
        cout << "Your character screams at the top of his lungs, " << endl;
        cout << "eventually your breath gives out and you die because of       lack of oxygen." << endl;
        system("pause");
        gameover();
¿Fue útil?

Solución

All other answers so far mention the need to use srand() to initialize your random number generator, which is a valid point, but is not the problem you're having.
Your problem is that your program computes the modulo of your random number and 1, which is always going to be equal to 0, because for any integer n,

n % 1 == remainder of the integer division of n by 1 
      == n - (n / 1) 
      == 0

So, replace this:

random1 = rand() % 1 + 0;

with this:

random1 = rand() % 2;

and you will have something that sort of does what you want. I'm saying "sort of" because there are other issues to consider, such as random number generator initialization (srand()), using rand() rather than more elaborate RNGs, etc.

Otros consejos

rand() can only generate pseudo random numbers, that is, the same seed will generate same sequence.
just use srand() to initialize seed, here is an example

#include <cctype>
#include <sys/time.h>
struct timeval cur_tm;
gettimeofday(&cur_tm, NULL);
seed = static_cast<unsigned int>(cur_tm.tv_usec);
srand(seed);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top