#Number guess program exercise

17 messages · Page 1 of 1 (latest)

young lantern
#

The following code works as expected except for 1 thing. The exercise in C++ Programming: Principles and Practice using C++ states the the computer should guess the user number in 7 attempts or less. Currently 8 is my best so far. I am not a student doing homework. I am an older guy self teaching. I am happy with this answer but wondering if someone can tell me what is wrong with the logic.

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include<cmath>
int number = 0;
char answer;
int min = 0;
int max = 100;
int average = 0;
int x = 0;

int main()
{
    std::cout << "Enter an integer number" << '\n';
    std::cin >> number;
    x = number;
    int guess_number = 0;

    while (x >= 0 && std::cin >> answer)
    {
        
        guess_number++;
        std::cout << "Average =\t" << average << '\n'
            << "Min =\t\t" << min << '\n'
            << "Max =\t\t" << max << '\n'
            << "x =\t\t" << x << '\n'
            << "This is guess number " << guess_number << '\n';
            average = (max + min) / 2;
            std::cout << "Is your number higher or lower than " << average << '\n'
            << "Answer:\th = higher\n\tl = lower" << '\n';
        
        switch (answer)
        {

        case 'h':
            
            if (x == average) { std::cout << "This is your number" << '\n'; }

            else if (x >= average)
            {
                average = (max + min) / 2;
                max = max;
                min = average;
            }        
            break;
        
        case 'l':
            
            if (x == average) { std::cout << "This is your number" << '\n'; }

            else if (x <= average)
            {
                average = (max + min) / 2;
                max = average;
                min = min;
            }
            break;
        }
    }
}```
#

Thank you to anyone who is willing to give some input.

mint cape
#

First point is global variables.
They are sometimes needed, but this is not one of those cases.
All your variables could live on main().

#

You should read "answer" after you ask the "Is your number higher or lower than" question.
Right now, you're dealing with the answer on the previous iteration.

young lantern
tiny walrus
#

8

young lantern
lusty joltBOT
#
Program Output
Enter an integer number
young lantern
# analog vapor ;compile cpp

I mean no disrespect. I know this server has a built in compiler but I haven't used it much.
I want to use it more just not sure how.

#

Can you tell me.more.

mint cape
#

If you want to fool around with the compiler to learn more about it, I would suggest doing so in #bot-spam.

#

Maybe you can find some inspiration from other posts there too?

analog vapor
young lantern
#

!solved

limber siloBOT
#

[SOLVED] Number guess program exercise

limber siloBOT
#

Number guess program exercise