简体   繁体   English

找到你想的数字的程序不能正常工作,有什么问题?

[英]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?界限很好,它缩小了猜测范围,直到它问我我想到的数字是否是 16,如果我输入“=”,它应该输出 16 而它总是输出 50。有人能帮我找到错误吗?

#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:您在深入研究递归函数时忘记更改b的值,这可以通过更改search函数轻松解决,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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