Making computer smarter

I was doing pretty fun exercise but I came across a problem when a task asked me to make computer guess in 7 or fewer times my number. I believe I need to add something in the if statements. 19th and 24th lines. What I'm thinking if the number is too high he (the computer) would stop guessing any numbers that are higher than the number he guessed previously. PLEASE don't give me the code but give me hints.

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
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
    int r, number, k = 0;
    cout << "What's your number 1-100 \n";
    cin >> number;
    while(r != number)
    {

        r = 1 + (rand() % 100);
        cout << r << endl;
        if(r == number)
        {
            cout << "You've guessed it finally \n";
            break;
        }
        else if(r > number)
        {
            cout << "Too high. \n";
            k++;
        }
        else if(r < number)
        {
            cout << "Too low. \n";
            k++;
        }
    }
    cout << "Computer, it took you: " << k << " times to guess my number." << endl;
    return 0;
}
Learn from your guesses. Keep track of what range the number can be in.

Random guessing is not necessarily the smartest strategy. Think how you can narrow the range as much as possible.
Yeah, you keep a lower and upper bound, and always guess in the middle.

lower = 0;
upper = 100;
guess = 50;

If it's higher, then lower = 50
If it's lower, then upper = 50

Rinse and repeat.
You do have an unrelated issue in:
1
2
3
int r, number, k = 0;
number = 42; // lets pretend that user wrote this
while( r != number )

You compiler should actually warn you about it, but perhaps it is not set verbose (or you missed the message).

Can you be sure that r != number is true on the first time?
If yes, why?
If no, why?
closed account (E0p9LyTq)
If you are going to use the C library for random numbers as the computer's choices you should seed the random number generator by calling srand() with the current computer time up at the beginning of main().

srand(time(nullptr)); // you need to include <ctime> for time()

Topic archived. No new replies allowed.