【问题标题】:Test for Palindrome using a recursive function in C使用 C 中的递归函数测试回文
【发布时间】:2013-04-10 08:58:15
【问题描述】:

我尝试编写用于测试字符串是否为回文的程序,但我总是得到输出,因为它不是回文。我的代码有什么问题?

#include <stdio.h>
#include <string.h>

int is_palindrome(int start, int end, char *str)
{
    if (str[start] != str[end])
        return 0;
    else if (start == end)
        return 1;
    else
        return is_palindrome(++start, --end, str);

    return 0;

}
int main()
{
    char str[20];
    int length,start=0,end=length-1;
    int result;
    printf("Enter the String.\n");
    fgets( str, sizeof( str ), stdin );
    length = strlen(str);

    if(is_palindrome(start,end,str))
        printf("It's a palindrome!\n");
    else
        printf("It's not a palindrome! \n");
    return 0;
}

【问题讨论】:

  • 在调试器中逐行逐行执行代码。并使用你知道是回文的字符串,最好是短的,这样更快。
  • int length,start=0,end=length-1; 长度在此处(还)没有值。
  • length 未设置为任何值,因此 end 是垃圾。
  • 我修复了这个问题,仍然得到相同的输出。
  • 调试程序时会发生什么?

标签: c function recursion logic


【解决方案1】:

++start--end 相互通过会发生什么?

else if (start == end)

应该是&gt;=

【讨论】:

    【解决方案2】:

    你有两个主要问题,

    1) 您正在使用length 初始化end,而没有先初始化length

    length = strlen(str);
    /* initialize end here */
    

    2) 您没有考虑在fgets 的字符串末尾获得的换行符:

    end = length - 2; /* don't include the newline */
    

    【讨论】:

      【解决方案3】:

      在这个is_palindrome()函数中你必须要检查它,否则它对回文词的偶数字符不起作用

      if(start>end)
          return 1;
      

      【讨论】:

        【解决方案4】:

        if(start==end) 所在行存在逻辑错误。

        这是由最后一次递归调用引起的,其中 last 和 end 的值将始终相同,即它们都将位于数组的中心。因此函数 is_palindrome() 将始终返回 1 并且输出将始终为 It's a palindrome!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-11-27
          • 1970-01-01
          • 2023-03-14
          • 2017-05-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多