gpt4 book ai didi

c - 字符串回文函数

转载 作者:太空宇宙 更新时间:2023-11-04 08:20:52 24 4
gpt4 key购买 nike

有一个简短的问题。

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

对于那些不知道回文是什么的人来说,基本上它是一组字符(通常是一个单词,但也可以是数字 - 尽管在这种情况下具体是单词),其前后拼写方式相同。

回文的例子 - wow, lol, 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;
}

这就是我的回文函数的样子。现在我只想检查来自标准标准输入的用户输入。

所以我的主要功能是这样的

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

非常简单的代码,不幸的是,我的结果是

"The word (word) is not a palindrome"

不管是不是回文。

所以我的功能可能完全有问题。我也知道这可以通过其他库来完成,例如 string.h 和其他库,但我个人更愿意以这种方式作为一种练习,而不是使用预定义的函数。

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

最佳答案

回文函数有多个错误

我们可以使用单个循环而不是循环中的循环。还要注意 for 循环的终止条件 start != (length/2) 以及 startend 的增量。

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

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

关于c - 字符串回文函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33480832/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com