用C程序回文 [英] Palindrome program in C

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

问题描述

我在C程序是回文在其功能的错误。我的功能是不是在我的字符串比较2个字符。当我输入一个字符它回答回文但如果是两个或更多的不总是回文。

My program in C which is Palindrome has an error in its function. My function is not comparing the 2 characters in my string. When I type a single character it answers palindrome but if it is two or more always not palindrome.

code:

          int IntStrlength=strlen(StrWord);
          int IntCtr2=0;
          int IntCtr=1, IntAnswer;
          while(IntCtr<=(IntStrlength/2)){
                printf(" %d %d\n", IntCtr2,IntStrlength);
               if(StrWord[IntStrlength] != StrWord[IntCtr2]){
                  IntAnswer=0;
                  printf(" %d=Not Palindrome", IntAnswer);
                  exit (0);
                 }//if(StrWord[IntCtr2]!=StrWord[IntStrlength]) <---------
               else{
                  IntCtr2++;
                  IntStrlength--;
                  }// else <--------
               IntCtr++;
          }//while(IntCtr<IntStrlength/2) <-----------
          IntAnswer=1;
          printf(" %d=Palindrome", IntAnswer);
          return ;

}

单字符:

两个或更多个字符:

推荐答案

为什么不写像这样

int wordLength = strlen(StrWord);
for (int i=0;i<(wordLength/2);i++) {
    if (StrWord[i] != StrWord[wordLength-i-1]) {
        return 0;
    }
}

return 1;

对于平均长度的话(比如8)计数器从0到3,访问所有的信件。对于不均匀的话(例如7)的C ounter会从0到2,留下中间元件选中。这不是因为它的回文必要的,它总是与自身匹配

For words with an even length (say 8) the counter will go from 0 to 3, accessing all letters. For uneven words (say 7) the c ounter will go from 0 to 2, leaving the middle element unchecked. This is not necessary since its a palindrome and it always matches itself

这篇关于用C程序回文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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