【问题标题】:this recursive function(palindrome) become a infinite loop.why?这个递归函数(回文)变成了一个无限循环。为什么?
【发布时间】:2014-10-24 20:14:24
【问题描述】:

/* 但如果我将第 13 行更改为“else return palindrome(s, ++f, --l);”然后代码运行良好。这是什么原因?*/

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

int palindrome(char* s, int f, int l)        // f = first index, l = last index; 
{
    if(f>=l) return 1;
    else if(s[f]!=s[l]) return 0;
    else return palindrome(s, f++,l--);
}

int main()
{
    char a[100];

    gets(a);
    int len = strlen(a)-1;
    printf("len: %d\n",len);
    int b = 0;

    if(palindrome(a, b , len))
    {
        printf("Plindrome\n");
    }
    else
    {
        printf("not palindrome\n");
    }
}

【问题讨论】:

  • 您显示的代码已经包含回文(s, ++f, --l) 行。

标签: c++ recursion infinite-loop palindrome


【解决方案1】:

签名

int palindrome(char* s, int f, int l)    

并呼吁

f = first index, l = last index;`

错了

++f/--l 对递归没有影响,除非你将它作为引用参数传递:

 int palindrome(char* s, int& f, int& l)
                         // ^       ^ Add a reference, if you're intending to change 
                         // the parameter value

【讨论】:

    【解决方案2】:

    让我猜猜。原来是

    palindrome(s, f++, --l)
    

    这意味着对于回文 f 的递归调用永远不会增加。它会在函数调用后递增。在你的情况下永远不会。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-04
      • 1970-01-01
      • 2020-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      相关资源
      最近更新 更多