You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 11:57:00