我这C语言“回文”错在哪儿?

来源:百度知道 编辑:UC知道 时间:2024/06/04 07:14:09
#define N 201
#include <stdio.h>
#include <string.h>
void main()
{
char a[N],b[N];
int i,n,b;
gets(a);
i=0;
n=-1;
while (a[i]!='\0')
{
i++;
n++;
}
b=n;
for (i=0;i<=b;i++)
{
b[i]=a[n];
n--;
}
if (strcmp(a,b)==0)
printf("yes\n");
else printf("no\n");
}

最明显的错误:
1. main函数第一行定义了名为b的数组,第二行又定义了一个b的int型变量,这个肯定行不通。
2.当然上面改了仍旧行不通,原因在于你虽然把b[i]赋值为了a[n],但现在b字符串并不是a字符串翻过来,因为字符串需要0结尾!
你在
for (i=0;i<=b;i++)
{
b[i]=a[n];
n--;
}
前加上b[i] = '\0';就ok了;
当然,我可以给你写一个稍微常见的回文的方法:

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

#define N 201
int main() {
char a[N], b[N];
int i;
gets(a);
int len = strlen(a);
bool is = true;
for(i = 0; i < len; i++) {
if(a[i] != a[len - i - 1]) {
is = false;
break;
}
}
if(is)
printf("yes\n");
else
printf("no\n");
return 0;
}

当然,你如果非要先把原来字符串翻转,再比较两个字符串的话:
#include <stdio.h>
#include <string.h>

#define N 201
int main() {
char a[N], b[N];
int i;
gets(a);
int len = strlen(a);
for(i = 0; i < len; i++)