简体   繁体   English

c++ 递归 function 条件满足时不会退出

[英]c++ recursive function wont exit when condition is meet

I need some help.我需要帮助。 I have a recursive function, in c++, that simply breaks apart a string(all numbers) and adds up the characters to see if its total is less than 9. if not it calls itself again until the condition is meet.我有一个递归的 function,在 c++ 中,它简单地拆分一个字符串(所有数字)并将字符相加以查看其总数是否小于 9。如果不是,它会再次调用自身直到满足条件。 So far everything it is working untill the end when my condition is meet it calls the function one more time.到目前为止,它一直在工作,直到满足我的条件为止,它再次调用 function。 This obviously messes up the value of the variable that I am trying to assign it to.这显然弄乱了我试图分配给它的变量的值。 I referred to many references and it seems like my syntax is correct?我参考了很多参考资料,我的语法似乎是正确的? Any help on why my function calls its self one last time.关于为什么我的 function 最后一次调用它自己的任何帮助。

///////////////////////////////////////////////////////// //////////////////////////////////////////////// ///////

int finalNumber =0;

// set finalNumber

finalNumber = sumTotal(sumInput);

int sumTotal(int sumInputToString)
{

    stringstream strToInt;
    string convertedInt;

    strToInt << sumInputToString;
    convertedInt= strToInt.str();

    int sum = 0;

    for(int i = 0; i < convertedInt.length(); i++)
    {
        sum += (int)convertedInt[i] - 48;
    }

    if (sum > 9)
    {
        sumTotal(sum);
    }
    return sum; //ONCE SUM IS LESS THAN 9,which is what i want, 
                //MY PROGRAM AUTOMATICALLY JUMPS UP TWO LINES does it one 
                //more time than it will escape.
}

I have tried everything from putting my return in a else{} and swapping my if else conditions so my return would be in my if.我已经尝试了所有方法,包括将我的回报放在 else{} 中并交换我的 if else 条件,这样我的回报就会在我的 if 中。 Any help would be greatly appreciated.任何帮助将不胜感激。

Thanks.谢谢。

Shouldn't the statement inside the condition be: 条件内的语句不应该是:

if (sum > 9)
{
    sum = sumTotal(sum);
}

Otherwise, you're just calling 不然你只是打电话

if (sum > 9)
{
    sumTotal(sum);
}
return sum;

which does nothing (ie doesn't contribute to the final output). 什么都不做(即对最终输出没有贡献)。

Based on this comment 基于此评论

MY PROGRAM AUTOMATICALLY JUMPS UP TWO LINES 我的程序自动跳两行

I may suggest you see this in the debugger. 我可能建议您在调试器中看到这一点。 Jumping up 2 lines itself is correct -- you move up on the function stack (ie return to the function which called yours -- and it is again sumTotal ). 向上跳两行本身是正确的-您在函数堆栈上向上移动(即返回调用您的函数-再次是sumTotal )。 So are you sure that after everything is done function really starts from the beginning? 那么,您确定在完成所有操作后,功能才真正从头开始吗?

One more thing to think about: if initial value of sumInputToString is less than 10 your code will be executed anyway. 还有一件事情要考虑:如果sumInputToString初始值小于10,您的代码将始终执行。 Do you want it really? 你真的想要吗?

And few advices not related with your question directly. 很少有与您的问题没有直接关系的建议。 It's very difficult to understand what your function should really do. 很难理解您的功能应该真正做什么。 For any complex algorithm (and this may be considered as complex because you use resursion) you must have a good function comment. 对于任何复杂的算法(由于使用递归,这可能被认为是复杂的),您必须具有良好的函数注释。 I would suggest something like this: 我建议这样的事情:

This function first calculates the sum of all digits in the given number. 此函数首先计算给定数字中所有数字的总和。 If the result is less or equal than 9 it is returned. 如果结果小于或等于9,则将其返回。 If not, we continue with this sum as a given number. 如果没有,我们继续将此和作为给定的数字。

You may also include short sentense why do you need it (because it may seem strange at the first glance): 您可能还会包括简短的句子,为什么需要它(因为乍看之下可能看起来很奇怪):

This function can be used to figure out whether some number is divisible by 3 or not. 此功能可用于确定某个数字是否可被3整除。

After wtirting such a comment you are starting to understand what the logic should be and may realize that you don't need a recursion here. 在添加了这样的注释之后,您开始了解逻辑应该是什么,并且可能会意识到您不需要在此处进行递归。 And transform your code into something like this: 并将您的代码转换为如下所示:

// Function comment
int CalculateRecursiveSumOfDigits(int val) {
    while (val > 9) {
        val = CalculateSumOfDigits(val); // TODO: implement this function
    }

    return val;
}

That's the least efficient way to steal your neighbor's electricity but sure..这是窃取邻居电力的最低效方式,但可以肯定的是……

Your program isn't jumping back two lines, your program popped the last recursion instance from the stack, you have to make sure that it would successfully exit the function call per nested function call.你的程序没有跳回两行,你的程序从堆栈中弹出最后一个递归实例,你必须确保它会成功退出每个嵌套的 function 调用 function 调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM