C语言 在 C 中使用递归函数测试回文
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16062723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Test for Palindrome using a recursive function in C
提问by Shail
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;
}
回答by djechlin
What happens when ++startand --endpass each other?
当++start和--end互相传递时会发生什么?
else if (start == end)
Should be >=.
应该是>=。
回答by perreal
You have two main issues,
你有两个主要问题,
1)You are initializing endusing lengthwithout first initializing length:
1)您正在初始化endusinglength而不先初始化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 */
回答by Samiul Alam Shamim
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;
回答by Kartik Thakral
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 i.e they both will be at the center of the array. Consequently the function is_palindrome()will always return 1and the output will always be It's a palindrome!
这是由最后一次递归调用引起的,其中 last 和 end 的值将始终相同,即它们都将位于数组的中心。因此,该函数is_palindrome()将始终返回1并且输出将始终为It's a palindrome!

