samedi 31 décembre 2016

PRNG program failure. Cannot enter random amount of choices and will always answer with 2 from the PRNG

So as the title describes I'm trying to learn PRNG but it hasn't gone too well thusfar. I am writing a program that takes an entered number of choices, rolls a dice and makes the choice for you. I do this using rand() and an array of strings with a length that is dependant on a variable read in before the declaration of the array.

The two problems showing up are that if I try to choose between for example 12 choices, the program will crash. As I read in the length of the array before I declare it I don't understand how this could happen. Also the PRNG will always return the number 2 which is not the desired function of a function that should return a random number between min and max. I will share my code below:

#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime> // for time()
#include <string>

using namespace std;

int callPRNG(int min, int max)
{
    srand(static_cast<unsigned int>(time(0))); // set initial seed value to system clock

    static const double fraction = 1.0 / (static_cast<double>(RAND_MAX) + 1.0);  // static used for efficiency, so we only calculate this value once
    // evenly distribute the random number across our range
    return static_cast<int>(rand() * fraction * (max - min + 1) + min);
}


int main()
{
    int max=1;
    int min=0;

    cout << "Please enter the amount of choices you want to choose from: ";
    cin >> max;
    string choices[max-1];
    int choiceMade=0;

    {
    int i=0;
        while(i<=max-1)
        {
            cout << "Please enter choice " << i+1 << ": ";
            cin >> choices[i];
            i++;
        }
        choiceMade=callPRNG(min, max-1);
        cout << "I have decided: " << choices[choiceMade-1];
    }

    return 0;
}

As extra information, I'm using code::blocks with C++11 enabled on a windows 10 OS. I hope someone can help me with this as I don't quite understand arrays and PRNG well enough to find the error by myself. Thanks :)

Aucun commentaire:

Enregistrer un commentaire