Member Avatar for vikingGamer

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 :)

Recommended Answers

All 4 Replies

Your number guess is wrong.

You should be guessing a number from randRangeX to randRangeY.

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

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
Member Avatar for vikingGamer

So I just change this line to what?

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.