字符 5:错误:控制可能到达非空函数的结尾

Gar*_*vit 1 c++ add while-loop

我是编程新手,我试图在 LeetCode 上解决这个问题,其中:

给定一个非负整数 num,重复将其所有数字相加,直到结果只有一位。输入:38 输出:2 解释:过程就像:3 + 8 = 11, 1 + 1 = 2。因为 2 只有一位数,所以返回它。

我的解决方案:

class Solution {
public:
    int addDigits(int num) {
        int sum =0,a =0;
        
        while(num!=0){
            a = num%10;
            sum = sum + a;
            num = num/10;          
        }
        
        if(sum>9){
            addDigits(sum);
        }else{
            return sum;
        }
        
    }
};
Run Code Online (Sandbox Code Playgroud)

此代码与其他编译器配合良好,但当我尝试在 LeetCode 提供的 IDE 上运行时出错

错误:

Line 18: Char 5: error: control may reach end of non-void function [-Werror,-Wreturn-type]
    }
    ^
1 error generated.
Run Code Online (Sandbox Code Playgroud)

请提出一种克服此错误的方法

Apl*_*123 5

在这一行:

addDigits(sum);
Run Code Online (Sandbox Code Playgroud)

您正在调用该函数,但您没有对其返回值执行任何操作。您必须实际返回值:

return addDigits(sum);
Run Code Online (Sandbox Code Playgroud)