得到了一个快速问题。
所以我试着在我的一个"初学者"程序中用C设计一个回文函数。
对于那些不知道回文是什么的人来说,基本上它是一组前后拼写相同的字符(通常是一个单词,但也可能是数字——尽管在这种情况下是单词)。
回文的例子-哇,哈哈,aaafaaa。。。
所以你明白了。所以我开始使用功能
int palindrome(char input[]){
所以我的假设是,理想情况下,我想遍历带有索引的字符串,并逐字母进行比较。
int palindrome(char input[]){
int start = 0, length = 0, end;
/* Until we reach end of the word */
while (input[start++] != ' '){
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;
}
所以那里的代码非常简单,不幸的是,我的结果是
"单词(word)不是回文"
不管它是否是回文。
所以我的函数可能有问题。我也知道这可以通过其他库来完成,比如string.h和其他库,但我个人更喜欢这样做,作为一种练习,而不是使用预定义的函数。
所以,是的,我强烈怀疑我没有在函数中正确使用返回,但我不确定它们的实际错误是什么。
回文函数中存在多个错误
我们可以使用单个循环,而不是循环中的循环。还要注意循环的终止条件start != (length / 2)
以及start
和end
的增量。
还修复了一些编译错误。完整的代码如下。
#include <stdio.h>
int palindrome(char input[]){
int start = 0, length = 0, end;
/* Until we reach end of the word */
while (input[length] != ' ')
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;
}
你的想法是正确的,只是有一些拼写错误和遗漏。
你的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++] != ' ')
length++;
并且CCD_ 6之前的CCD_。
并且int start = 0
不是必需的,因为无论如何都要在for循环开始时初始化start
;CCD_ 9就足够了。但这并不是一个真正的错误。