简体   繁体   English

使用C中的递归函数测试回文结构

[英]Test for Palindrome using a recursive function in C

I tried to write the program for testing a string if it's a palindrome or not, but I always get the output as it's not one. 我尝试编写用于测试字符串的程序,如果它是一个回文或不是,但我总是得到输出,因为它不是一个。 What's wrong with my code? 我的代码出了什么问题?

#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;
}

What happens when ++start and --end pass each other? ++start--end传递时会发生什么?

else if (start == end)

Should be >= . 应该>=

You have two main issues, 你有两个主要问题,

1) You are initializing end using length without first initializing length : 1)您正在使用length初始化end而不首先初始化length

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

2) You are not considering the newline you get at the end of the string from fgets : 2)你没有考虑从fgets到字符串末尾的换行符:

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

In this is_palindrome() function you must need to check it otherwise it will not work for the even number character of palindrome word 在这个is_palindrome()函数中你必须检查它否则它将不适用于回文词的偶数字符

if(start>end)
    return 1;

On the line with if(start==end) there is logical error. if(start==end)有逻辑错误。

This is caused by the last recursive call, where the value of last and end will always be same ie they both will be at the center of the array. 这是由最后一次递归调用引起的,其中last和end的值总是相同的,即它们都将位于数组的中心。 Consequently the function is_palindrome() will always return 1 and the output will always be It's a palindrome! 因此,函数is_palindrome()将始终返回1 ,输出将始终是It's a palindrome!

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

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