C++实现的猜数字递归程序最终总是输出50,如何排查错误?
问题根因
你的代码核心问题是递归调用没有返回对应结果:当前逻辑下,只有当用户输入=的时候,才会直接返回当前层级计算的b值;如果是<或>分支,你只是调用了search函数,但没有接收它的返回值,函数最终还是会返回当前层级计算出的初始b值(也就是第一层调用的(1+100)/2=50),这就是你不管最后猜中什么都输出50的原因。
修复方案
只需要在两个递归调用的语句前加上return关键字,把深层递归的返回值逐层传回来即可,同时可以优化边界逻辑避免相邻数字判断时出现死循环:
#include <iostream> #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 = (boundSup + boundInf) / 2; cout << "Is your number <, > or = to " << b << "? "; cin >> magnitude; if (magnitude == "<") { cout << "Between " << boundInf << " and " << b << endl; return search(boundInf, b - 1); // 新增return,同时边界减1避免重复猜相同值 } else if (magnitude == ">") { cout << "Between " << b << " and " << boundSup << endl; return search(b + 1, boundSup); // 新增return,同时边界加1避免重复猜相同值 } return b; }
错误定位通用方法
- 可以在
search函数的return b语句前加打印语句,输出每次返回的b值,就能看到第一层调用最终返回的是初始计算的50,而不是最后猜中的值 - 也可以用IDE的断点调试功能,跟着递归调用栈查看每层的返回值,很快就能发现深层递归的结果没有被上层接收的问题
内容的提问来源于stack exchange,提问作者pat
相关产品推荐
相关产品推荐

