C 字符串回文函数

C 字符串回文函数,c,C,我有个简短的问题 所以我尝试在我的一个“初学者”程序中用C语言设计一个回文函数 对于那些不知道回文是什么的人来说,基本上它是一组字符(通常是一个单词,但也可以是数字——虽然在本例中具体是单词),前后拼写相同 回文的例子-哇,哈哈,aaafaaa 你说得对。所以我从我的功能开始 int回文(字符输入[]){ 因此,我的假设是,理想情况下,我希望使用索引遍历字符串,并逐个字母进行比较 int palindrome(char input[]){ int start = 0, length = 0,

我有个简短的问题

所以我尝试在我的一个“初学者”程序中用C语言设计一个回文函数

对于那些不知道回文是什么的人来说,基本上它是一组字符(通常是一个单词,但也可以是数字——虽然在本例中具体是单词),前后拼写相同

回文的例子-哇,哈哈,aaafaaa

你说得对。所以我从我的功能开始

int回文(字符输入[]){

因此,我的假设是,理想情况下,我希望使用索引遍历字符串,并逐个字母进行比较

int palindrome(char input[]){
 int start = 0, length = 0, end;
 /* Until we reach end of the word */
 while (input[start++] != '\0'){
   length++;

   for(start = 0, end = length - 1; start = length / 2; end--){
   /*If they do not match, return 0 */
     if (input[start] != input[end]){
        return 0;
        break;
     }
   }
 }
return 1;
}
这就是我的回文函数的样子。现在我只想检查标准stdin中的用户输入

我的主要功能如下所示

int main(){
char uInput[30];

/* Welcome user */
printf("Hello, please enter some text \n);
scanf("%29s", uInput);

if palindrome(uInput){
printf("The word: %s is a palindrome \n", uInput);
}

else {
printf("The word: %s is not a palindrome \n", uInput);
}

return 0;
}
非常简单的代码,不幸的是,我的结果是

“这个词不是回文”

不管它是否是回文

因此,我的函数可能完全有问题。我也知道这可以通过其他库(如string.h和其他库)来完成,但我个人更喜欢这样做,作为一种练习形式,而不是使用预定义函数


是的,我强烈怀疑我在函数中没有正确使用返回值,但我不确定返回值的实际错误是什么。

你的想法是正确的,只是有一些输入错误和遗漏

您的for循环错误,应该是:

for(start = 0, end = length - 1; start != length / 2; start++, end--)
而不是:

for(start = 0, end = length - 1; start = length / 2; end--)
你的while循环也包括整个for循环,这是胡说八道。 应该是:

while (input[start++] != '\0')
  length++;
并且应该删除返回1之前的
}


并且
int start=0
是不必要的,因为您无论如何都要在for循环的开头初始化
start
<代码>整数开始就足够了。但这并不是一个真正的错误。

回文函数中存在多个错误

我们可以使用单个循环,而不是循环中的循环。还要注意终止条件
start!=(长度/2)
for循环和
开始和
结束的增量

还修复了一些编译错误。完整的代码如下

#include <stdio.h>
int palindrome(char input[]){
 int start = 0, length = 0, end;

 /* Until we reach end of the word */
 while (input[length] != '\0')
   length++;

 for(start = 0, end = length - 1; start != (length / 2); start++, end--){
 /*If they do not match, return 0 */
     if (input[start] != input[end]){
        return 0;
     }
 }

 return 1;
}

int main(){
char uInput[30];

/* Welcome user */
printf("Hello, please enter some text \n");
scanf("%29s", uInput);

if (palindrome(uInput)){
printf("The word: %s is a palindrome \n", uInput);
}

else {
printf("The word: %s is not a palindrome \n", uInput);
}
return 0;
}
#包括
整型回文(字符输入[]){
int开始=0,长度=0,结束;
/*直到我们到达世界的尽头*/
while(输入[长度]!='\0')
长度++;
对于(开始=0,结束=长度-1;开始!=(长度/2);开始++,结束--){
/*如果它们不匹配,则返回0*/
如果(输入[开始]!=输入[结束]){
返回0;
}
}
返回1;
}
int main(){
字符输出[30];
/*欢迎用户*/
printf(“您好,请输入一些文本\n”);
scanf(“%29s”,输入);
if(回文(uInput)){
printf(“单词:%s是回文\n”,uInput);
}
否则{
printf(“单词:%s不是回文\n”,uInput);
}
返回0;
}

如果回文(uInput),是否也需要在
for
循环中移动
start
{
编译器没有对此给出任何警告吗?请发布您已经测试过的真实代码,您在这里的内容将给出各种编译错误。@ameyCU没有,尽管请记住我没有在这里粘贴我的全部代码,只有两个相关的函数。此外,我注意到我在一句话中漏掉了引号,在翻译时也漏掉了其他一些东西抄写的东西,所以请不要使用它作为一个领先的例子。准确地说,我使用了gcc和gnu,没有遇到任何错误,从下面张贴的两个答案的建议。