gpt4 book ai didi

c - 我在这个 C 程序中检查字符串是否是回文时做错了什么?

转载 作者:行者123 更新时间:2023-11-30 19:29:51 25 4
gpt4 key购买 nike

下面是我编写的C程序,用于检查输入的字符串是否是回文,但它总是显示“else”语句,即该字符串不是回文:-

#include<stdio.h>
#include<string.h>
void main()
{
int i,n,count=0;
char f[30];
printf("Enter the string. : ");
gets(f);
n = strlen(f);

for(i=0;i<n;i++)
{
if(f[i+1]==f[n-i])
count=count+1;
}
if(count==n)
printf("\n Entered string is Palindrome");
else
printf("\n Entered string is NOT Palindrome");

}

最佳答案

i = 0时,f[n-i]将是终止空字符,它永远不会出现在字符串的中间。因此,如果字符串长度为 2 个字符或更长,则条件 f[i+1]==f[n-i] 将为 false。(如果字符串的长度为 1 个字符,则 f[i+1] 将是第一个(也是唯一的)字符之后的终止空字符,因此条件将为 true。)

条件应为f[i]==f[n-i-1]

顺便说一下,

  • 您不应使用 gets(),它存在不可避免的缓冲区溢出风险,在 C99 中已弃用并已从 C11 中删除。
  • 您应该在托管环境中使用标准 int main(void) 而不是 void main(),这在 C89 中是非法的,并且在 C99 或更高版本中是实现定义的,除非您有特殊原因使用此非标准签名(例如,老板或老师强制您使用此签名)。

完整固定代码的示例:

#include<stdio.h>
#include<string.h>
int main(void)
{
int i,n,count=0;
char f[30 + 1]; /* allocate one more element for storeing newline character */
char* lf;
printf("Enter the string. : ");
fgets(f, sizeof(f), stdin); /* change gets() to fgets() */
/* fgets() stores newline character while gets() doesn't, so remove it */
if ((lf = strchr(f, '\n')) != NULL) *lf = '\0';
n = strlen(f);

for(i=0;i<n;i++)
{
if(f[i]==f[n-i-1])
count=count+1;
}
if(count==n)
printf("\n Entered string is Palindrome");
else
printf("\n Entered string is NOT Palindrome");

}

关于c - 我在这个 C 程序中检查字符串是否是回文时做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52279432/

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