首页 文章

布尔递归函数返回错误的值

提问于
浏览
0

这是一个递归函数,我发现如果一个数字中的给定数字是递减顺序,我确定我的基数是正确的,因为我看到函数确实返回前几位数的假,但因为最后两个按顺序递减,函数最后返回true .

我无法弄清楚如何保持该假值并将其返回到函数的原始调用 .

#include<iostream>
using namespace std;
bool dec(int n);

void main()
{
    cout << dec(1231);
}

bool dec(int n)
{
    bool res;

    if (n < 10)
        return true;
    else
    {
        res = dec(n / 10);
        if ((n / 10) % 10 > n % 10)
            return true;
        else
            return false;
    }
}

1 回答

  • 1

    你应该只有 return true 如果 res 也是如此 . 尝试

    return (res && (n / 10) % 10 > n % 10);
    

相关问题