为什么我的 bool return 语句 returning 不是 0 或 1?

Why is my bool return statement returning something other than 0 or 1?

我有一个 bool 函数,它执行一些计算并检查某些条件是否为真。如果是这样,它 returns true 或 false,作为 bool 函数应该。

但是,当它为真时,它不会返回 1,而是 returns 个随机数,例如 48、240、112、224 等

我确定您需要代码...在这里:

bool isHappy(int n) {
        if (n < 10) return false;
        
        int sumSquares = 0;
        vector<int> nums;
        string length = to_string(n);

        for (int i = 0; i < length.size()-1; i++) {
            nums.push_back(n % 10);
            if (n >= 10) n = n / 10;
        }   
        
        for (int i = 0; i < nums.size(); i++) {
            sumSquares += (nums[i] * nums[i]);        
        }
        
        sumSquares += (n * n);

        if (sumSquares == 1) {
          return true; // <--This is the line that seems to cause the problem
        } else {
          isHappy(sumSquares);
        }
    return 0;
    }

int main() {
  int testNumber = 19; 
  cout << isHappy(testNumber);
}

看起来你尝试实现递归函数是不正确的。

isHappy(sumSquares);

应该是

return isHappy(sumSquares);