简体   繁体   English

C ++数字计数怪异错误

[英]C++ Digit Counting Weird Error

I have a very weird error. 我有一个很奇怪的错误。 I have a very simple digit counting function. 我有一个非常简单的数字计数功能。 The function is going in an infinite loop if I do this: 如果执行此操作,则函数将陷入无限循环:

int numOfDigits(int num, int count)
{
    while(num != 0) {
        count++;
        numOfDigits(num/10, count);
    }
    return count;
}

But it works this way: 但是它是这样工作的:

int numOfDigits(int num, int count)
{
    while(num != 0) {
        count++;
        num /=10;
        numOfDigits(num, count);
    }
    return count;
}

I tried using gdb but couldn't figure out. 我尝试使用gdb,但无法弄清楚。 I'm compiling with g++ on Ubuntu 14.04. 我正在Ubuntu 14.04上使用g ++进行编译。

while(num != 0) {
  count++;
  numOfDigits(num/10, count);
}

This while-loop never terminates, because num is never actually modified. 该while循环永远不会终止,因为num从未真正修改过。 Thus it will never exit the loop if the condition wasn't false in the first place. 因此,如果条件最初不是假的,它将永远不会退出循环。

int numOfDigits(int num, int& count)
{
    if(num != 0) {
        count=1+numOfDigits(num/10, count);
    }
    return count;
}

I have changed count as being passed by reference though it is not really required. 我已将count更改为通过引用传递,尽管这并不是真正需要的。 You have the while loop that goes on infinitely because num is not modified in that context. 您拥有while循环无限进行的原因,因为在该上下文中未修改num You are mixing iteration and recursion. 您正在混合迭代和递归。

Recursive functions require two things: 递归函数需要两件事:

  1. A terminating condition 终止条件
  2. A reducing clause 归约条款

In your first example, you had the terminating condition num != 0 ...but not the reducing clause as @WorldSEnder pointed out ( num was totally unaffected). 在第一个示例中,终止条件为num != 0 ...但没有@WorldSEnder指出的减少条件子句( num完全不受影响)。

Also, there's no rule against iteration in recursion...but it usually makes things more complicated than it should be. 另外,递归中没有禁止迭代的规则...但是,这通常会使事情变得复杂得多。

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

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