0

I'm learning with a book and one of the excercises is to have the computer guess a number of which you think. My problem is that I need to keep altering the range which works for a couple tries then it seemingly forgets the range and goes on its own.

//Computer guesses your number

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

using namespace std;

int main () {
    char yourNumber;
    int randRangeY = 100;
    int randRangeX = 1;
    int secretNumber = 1;
    srand (time(NULL));

    while(yourNumber != 'y')
    {
        if (yourNumber == 'h')
        {
            randRangeX = (secretNumber+1);
        }
        else if (yourNumber == 'l')
        {
            randRangeY = (secretNumber-1);
        }

        secretNumber = (rand()%randRangeY)+randRangeX;
        cout << randRangeX << "," << randRangeY << endl;

        cout << "Is it " << secretNumber << "? (h/l/y)" << endl;
        cin >> yourNumber;

    }

    cout << "Awesome";
    return 0;
}

Thank you for your help :)

Edited by vikingGamer

3
Contributors
4
Replies
28
Views
1 Year
Discussion Span
Last Post by Nutster
0

Your number guess is wrong.

You should be guessing a number from randRangeX to randRangeY.

Instead, you're guessing from randRangeX to (randRangeX+randRangeY).

Edited by Moschops

0

Guessing the middle of the range to make things faster. Using a random number in the range just adds extra complexity and extra guesses.

Is your number 50? L
Is your number 25? H
Is your number 37? L
Is your number 31? L
Is your number 34? Y
0

So I just change this line to what?

secretNumber = (rand()%randRangeY)+randRangeX;
0

To get a random number between X and Y, you need to specify the range of valid values. You need to tell it how many numbers are valid and the starting value. If you want the numbers 7, 8, 9, or 10, you have 4 numbers with a starting value of 7. So the range is the largest value minus the smallest value, but then you have to add one. 10-7 = 3, then add 1 to get 4.
secretNumber = (rand() % (randRangeY - randRangeX + 1)) + randRangeX

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.