当使用C递归函数测试回文 [英] Test for Palindrome using a recursive function in C

查看:135
本文介绍了当使用C递归函数测试回文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着写程序来测试一个字符串,如果它是一个回文或没有,但我总是得到输出,因为它是一个也没有。这有什么错我的code?

 的#include<&stdio.h中GT;
#包括LT&;&string.h中GT;INT is_palindrome(INT开始,诠释年底,焦炭*海峡)
{
    如果(STR [开始]!= STR [结束])
        返回0;
    否则,如果(开始==结束)
        返回1;
    其他
        返回is_palindrome(++开始,--end,STR);    返回0;}
诠释的main()
{
    焦炭海峡[20];
    INT长度,起始= 0,结束=长度为1;
    INT结果;
    的printf(请输入字符串\\ n);
    与fgets(海峡,sizeof的(STR),标准输入);
    长度= strlen的(STR);    如果(is_palindrome(起点,终点,STR))
        的printf(这是一个回文\\ n!);
    其他
        的printf(这不是一个回文\\ n!);
    返回0;
}


解决方案

您有两个主要问题,

1)您正在初始化结束使用长度不首先初始化长度

 长度= strlen的(STR);
/ *初始化结束这里* /

2)您是不考虑你得到的字符串的结尾换行符与fgets

 结束=长度 -  2; / *不包括新行* /

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

解决方案

You have two main issues,

1) You are initializing end using length without first initializing length:

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

2) You are not considering the newline you get at the end of the string from fgets:

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

这篇关于当使用C递归函数测试回文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆