我正在尝试编写一个 C 程序,它吃掉一个先验有界长度的字符串,如果它是回文则返回 1,否则返回 0。我们可以假设输入由小写字母组成。
这是第一门编程类(class)的一部分,所以我没有经验。
这是我的尝试。一旦我尝试在 CodeBlocks 上构建/运行它,程序就会关闭。很遗憾,因为我认为我做得很好。
#include <stdio.h>
#define MaxLength 50
int palindrome(char *a,int size) /* checks if palindrome or not */
{
int c=0;
for(int i=0;i<size/2;i++) /* for every spot up to the middle */
{
if (*(a+i)!=*(a+size-i-1)) /* the palindrome symmetry condition */
{
c++;
}
}
if (c==0)
{
return 1; /*is palindrome*/
}
else
return 0; /*is not palindrome*/
}
int main()
{
char A[MaxLength]; /*array to contain the string*/
char *a=&A[0]; /*pointer to the array*/
int i=0; /*will count the length of the string*/
int temp;
while ((temp=getchar())!='\n' && temp != EOF) /*loop to read input into the array*/
{
A[i]=temp;
i++;
}
if (palindrome(a,i)==1)
printf("1");
else
printf("0");
return 0;
}
备注。我现在要 sleep 了,所以几个小时内我不会有任何反应。
最佳答案
你的方法是好的,虽然你有一些小错误。首先,#define MaxLength=50
应该是 #define MaxLength 50
(要替换的文本,空格,然后是它的替换)。
您还应该在 main()
之前为您的 palindrome()
函数提供一个原型(prototype):
int palindrome(char *a,int size);
...或者只是将整个palindrome()
函数移动到main()
之上。原型(prototype)或实际函数定义应该出现在对函数的任何调用发生之前。
下一个问题是您正在寻找输入字符串末尾的空字符。 C 字符串通常以 null 终止,但来自控制台的行不是(如果有终止符,它会在您的程序决定结束字符串时添加)——您可能应该检查换行符(理想情况下) , 对于错误也是如此)。所以不是
while ((temp=getchar())!='\0')
尝试
while ((temp=getchar())!='\n' && temp != EOF)
当你在 main()
中打印你的结果时,你应该在末尾有一个换行符,例如。 printf("1\n");
而不是 printf("1");
,以确保刷新输出缓冲区,以便您可以看到输出以及结束该输出行。
那么在您的 palindrome()
函数中,您的 for
循环语法是错误的——这三个部分应该用分号而不是逗号分隔。所以改变:
for(int i=0,i<size/2,i++)
...到:
for(int i=0; i<size/2; i++)
您还有一个额外的右大括号供循环体移除。
在修复所有这些之后,它似乎可以工作...
关于检查字符串是否为回文 - 当我编译程序时关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42309770/