dimanche 10 septembre 2017

Random number generator not generating within set variable parameters

Forgive me if this is a simple question, I'm extremely new to coding, but I've been trying to create a program in which the user thinks of a number and the computer tries to guess it using parameters on a random number generator.

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>

using namespace std;

int main()
{
    srand(static_cast<unsigned int>(time(0))); //seed random number generator
    int guess = (rand() % 100) + 1; //random number between 1 and 100
    int turns = 1;
    int max = 100;
    int min = 1;

    cout << "Pick a number between 1 and 100 then press enter." << endl;
    cin.get();

    string responce = "n";
    cout << "Was " << guess << " your number? Y/N" << endl;
    cin >> responce;

    while (responce == "n" || responce == "N")
    {
        ++turns;

        string lowresponce;
        cout << "Was the number too low?" << endl;
        cin >> lowresponce;

        if (lowresponce == "y" || lowresponce == "Y")
        {
            min = guess; //this statement should (?) set the minimum number to whatever was guessed.
            guess = (rand() % max) + min; //then this should calculate a number between the minimum (which is the last number guessed) and the maximum
        }
        if (lowresponce == "n" || lowresponce == "N")
        {
            max = guess;
            guess = (rand() % max) + min;
        }

        cout << "Was " << guess << " your number? Y/N" << endl;
        cin >> responce;
    }

    cout << "I guessed your number, " << guess << ", in " << turns << " turns!" << endl;

    return 0;
}    

Occasionally, a number will generate out of the set parameters, like so, and for the life of me I cannot understand why.

Results of test run:

Number = 60

1st guess = 72, max set to 72

2nd guess = 39, min set to 39

3rd guess = 45, min set to 45

4th guess = 99, which is out of the range, (45,72), and shouldn't have been a guess in the first place.

Any ideas as to why this is happening?




Aucun commentaire:

Enregistrer un commentaire