简体   繁体   中英

Program that finds the number you are thinking doesn't work properly, what is wrong?

Im having trouble with this recursion code. Basically I want the computer to "guess" in as little steps as possible the number that I am thinking of. However, everything works except the final output. The bounds are fine, and it narrows down the guess until it asks me if the number im thinking of is say 16, if I input "=" it should output 16 instead it always outputs 50. Could anyone help me locate the error?

#include <iostream>
#include <cmath>
#include <string>

using namespace std;

unsigned int search (unsigned int boundInf, unsigned int boundSup);

int main ()
{
    int b;
    b = search (1, 100);

    cout << "Your number must be : " << b << endl;
}

unsigned int search (unsigned int boundInf, unsigned int boundSup)
{
    string magnitude;
    int b;
    b = (boundSup + boundInf) / 2;
    
    cout << "Is your number <, > or = to " << b << "? ";
    cin >> magnitude;

    if (magnitude == "<") {
        cout << "Between " << boundInf << " and " << b << endl;
        search (boundInf, b);
    }
    else if (magnitude == ">") {
        cout << "Between " << b << " and " << boundSup << endl;
        search (b, boundSup);
    }
    
    return b;
}

You forgot to change the value of b when going deeper into the recursive function, this can be easily fixed by changing the search function like so:

unsigned int search(unsigned int boundInf, unsigned int boundSup)
{
    string magnitude;
    int b;
    b = (boundSup + boundInf) / 2;
    cout << "Is your number <, > or = to " << b << "? ";
    cin >> magnitude;

    if (magnitude == "<")
    {
        cout << "Between " << boundInf << " and " << b << endl;
        b = search(boundInf, b);
    }
    else if (magnitude == ">")
    {
        cout << "Between " << b << " and " << boundSup << endl;
        b = search(b, boundSup);
    }

    return b;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM