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

Time:10-25

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;
}

CodePudding user response:

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;
}
  •  Tags:  
  • c
  • Related