1

文字列が回文であるか、ライブラリ string.h を使用していないかを教えてくれるプログラムを実行する必要があります。次のコードを書きましたが、出力は常に「回文」です

#include<stdio.h>
#include<conio.h>
#include<string.h>

int main()
{
 char a[100],b[100]; 
 int i,k;  
 printf("Type the string \n");
 gets(a);
 k=strlen(a);
 for(i=0;i<strlen(a);i++)
 {
  a[i]=b[k]; 
  k--;                       
 }           //at the end of this code the string "b" should be the reverse of "a"
 k=strcmp(a,b);
 if (k!=0)   //here I check if a=b or not
 {printf("palindrome");}
 else
 {printf("not palindrome");}
 getch();
 return 0;
}

例: 入力が「非」の場合、出力は「回文」である必要があり、入力が「船」の場合、出力は「回文ではない」である必要があります。誰が間違っているかを見つけるのを手伝ってくれますか?

4

5 に答える 5

4

ラインだと思います

a[i]=b[k];

b[k]これは、 (初期化していない)の内容を( a[i]get で入力した) に入れませんか? これにより、a のテスト値が空白で上書きされます (または、b のメモリにあったものは何でも)。反対のことをすべきではありませんか?

ただし、まったく実行しない方がよいでしょう。配列内の文字を比較するだけです。

k=strlen(a);
for(i=0; i<k/2; i++)
   if(a[i] != a[k-i]) 
      return "Not Palindrome";
return "Palindrome";                    
于 2013-04-07T14:45:55.387 に答える
0

私はあなたのためにそれを修正しました、コメントに注意してください:

#include<stdio.h>
#include<conio.h>
#include<string.h>

int main()
{
     char a[100],b[100]; 
     int i;
     int stringLen;  
     printf("Type the string \n");
     gets(a);
     stringLen = strlen(a);
     for(i=0; i < stringLen; i++)
     {
         //First you want to copy to B not A...
         //second, you need to remove "1" from the size cause array start from "0".
         b[stringLen-1-i] = a[i];            
     }//at the end of this code the string "b" should be the reverse of "a"

     if (strcmp(a,b) == 0)   //0 mean equal !
     {
         printf("palindrome");
     }
     else
     {
         printf("not palindrome");
     }
     getch();
     return 0;
}
于 2013-04-07T14:53:59.210 に答える
0

strcmp()両方の文字列が等しい場合、ゼロ値を返します。次のようなものでなければなりません。

#include<stdio.h>
#include<conio.h>
#include<string.h>

int main()
{
    char a[100],b[100]; 
    int i,k;  
    printf("Type the string \n");
    gets(a);
    k=strlen(a)-1;
    for(i=0;i<strlen(a);i++)
    {
        b[i]=a[k]; //assign to b not to a
        k--;                       
    }
    b[strlen(a)]='\0';//terminate the string with null character
    //at the end of this code the string "b" should be the reverse of "a"
    k=strcmp(a,b);
    if (k==0)   //here I check if a=b or not
    {printf("palindrome");}
    else
    {printf("not palindrome");}
    getch();
    return 0;
}
于 2013-04-07T14:54:13.440 に答える