【问题标题】:The following code for palindrome doesn't work?is there a logical mistake?以下回文代码不起作用?是否存在逻辑错误?
【发布时间】:2014-12-07 13:05:42
【问题描述】:

有人能指出这段代码中的错误吗?我正在使用codingblocks IDE。

#include <stdio.h>
main()
{
    char a[100],b[100];int i,j=0; 
    scanf("%s",&a);
    for(i=strlen(a)-1,j=0;i>=0;i--)
    {
        b[j]=a[i];
        j=j+1;
    }
    b[j]='\0';
    if(a==b) # on printing i get both 'a' and 'b' as equal however this condition still remains
             # false

        printf("true"); #doesnot print?

}

【问题讨论】:

标签: c logic palindrome


【解决方案1】:

更改此语句

if(a==b)

if ( strcmp( a, b ) == 0 )

否则,您将比较数组的第一个元素的地址。

您还需要包含标题&lt;string.h&gt;。函数 main 应具有返回类型 int。更改此语句

scanf("%s",&a);

scanf( "%s", a);

考虑到不需要定义第二个数组来确定字符串是否为回文。您可以“就地”执行此检查。

【讨论】:

    【解决方案2】:

    代码中的一些问题

    • 您从不复制 b 中的任何内容,因此该数组具有随机字符。

    • a==b 将始终为 false,因为它们是字符数组而不是指针,并且都包含不同的值。

    • 如果你正在读取字符串,你不需要&amp;作为char数组,所以scanf()应该是scanf("%s",a);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-16
      • 2013-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-27
      • 1970-01-01
      相关资源
      最近更新 更多