Setting dynamic bounds for rand()

OK so im trying to do a program that will guess your number you choose. You tell it either too high, or too low, and it continues to guess. If you say too high, the upper bound should be set to that last guessed value. Same goes for lower bound. But, this doesnt happen. I just continue to get the initial range of numbers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
void NumberGuess(int targetNumber)
{
    srand(time(NULL));
    int randomNumber = rand() % 100 + 1;
    int upperBound;
    int lowerBound;
    int choice;
    bool numGuessed = false;

    while(numGuessed == false)
    {
        cout << "Here's my guess " << randomNumber << endl;
        cout << "Was my number too high, too low, or correct?\n";
        cout << "1. Too high.\n";
        cout << "2. Too low.\n";
        cout << "3. Correct!\n";
        cin >> choice;
        if(choice == 1)
        {
            upperBound = randomNumber;
            randomNumber = (rand() % upperBound) + 1;
        }
        else if(choice == 2)
        {
            lowerBound = randomNumber;
            randomNumber = (rand() % 100) + lowerBound;
        }
        else if(choice == 3)
        {
            cout << "Cool! Told you I could guess it!\n";
            numGuessed = true;
        }
    }
}

If R is a random number in any range, R%X will be a random number in range [0; X)
If S is a random number in some range [A; B], S+Y will be a random number in range [A+Y; B+Y].

So, in rand()%x+y, x is the distance form lowest to highest value and y is the lowest value.
Your rand lines should be rand()%(upper-lower)+lower.
Ok so I changed it to

1
2
3
4
5
6
7
8
9
10
if(choice == 1)
        {
            upperBound = randomNumber;
            randomNumber = rand() & (upperBound - lowerBound) + lowerBound;
        }
        else if(choice == 2)
        {
            lowerBound = randomNumber;
            randomNumber = rand() & (upperBound - lowerBound) + lowerBound;
        }


And now the output I get is just either 0 or 64. And it tends to stick on 64 for a good few guesses.
randomNumber = rand() % (upperBound - lowerBound + 1) + lowerBound;
Oh and lowerBound is initialised at 1 and upperBound at 100
Oh wow! Ok, that was a dumb mistake. I really shouldn't do this with 3 hours of sleep. & is not the same as %
:/
Topic archived. No new replies allowed.