我正在做一项作业,我必须在该处接受用户的句子输入,以相反的顺序打印单词,检查字谜和回文。我有一个适用于字谜的功能,而我的回文功能几乎可以正常工作。现在,我只要求输入两个单词,这样我的功能就可以正常工作了。但是,由于某些原因,每当我为我要的两个单词输入一个冗长的回文(例如:赛车或比妈妈或爸爸都减速的时候),回文功能就会混乱。
这是代码;
#include <stdio.h>
#include <ctype.h> //Included ctype for tolower / toupper functions
#define bool int
#define true 1
#define false 0
//Write boolean function that will check if a word is a palindrome
bool palindrome(char a[])
{
int c=0;
char d[80];
//Convert array into all lower case letters
while (a[c])
{
a[c] = (tolower(a[c]));
c++;
}
c = 0;
//Read array from end to beginning, store it into another array
while (a[c])
c++;
while(a[c] != 0 && c > -1)
{
d[c] = a[c];
c--;
}
c = 0;
while(a[c])
{
printf("%c", d[c]);
printf("%c", a[c]);
c++;
}
//If two arrays are equal, then they are palindromes
for(c = 0; a[c] && d[c]; c++)
{
while(a[c] && d[c])
{
if(a[c] != d[c])
return false;
}
}
return true;
}
int main(void)
{
char a[80], b[80];
bool flagp;
//Prompt user to enter sentence
printf("Enter a word: ");
gets(a);
flagp = palindrome(a);
if (flagp)
{
printf("\nThe word is a palindrome.");
}
else
{
printf("\nThe word is not a palindrome.");
}
return 0;
}
它输出这个;
Enter first word: racecar
_r▬a↨c e c a r
The word is not a palindrome.
但是,如果我输入“ racecar”,则会错误地指出这不是回文。
请告诉我我在做什么错:'(
a[c] != d[c]
当你想到它是假的是真的。printf
证明这是因为d[c]
是垃圾。d
不包含的相反符号a
。因此,这导致人们检查以下代码段:
while(a[c] != 0 && c > -1)
{
d[c] = a[c];
c--;
}
它正在尝试创建反向副本,但是很显然,由于它所放置的索引与所获取的索引相同,因此它在反转任何看到的内容时都失败了。
(您执行了前三个步骤。为什么要在这里停下来?)
老实说,根本没有理由d
存在。所有这些都可以就地完成。
+---+---+---+---+---+---+---+
a: | r | a | c | e | c | a | r |
+---+---+---+---+---+---+---+
^ ^
| compare these two |
^ ^
| then these |
...
因此,代码如下所示:
size_t len = strlen(a);
if (len) {
size_t i = 0;
size_t j = len - 1;
while (i < j) {
if (a[i++] != a[j--])
return 0;
}
}
return 1;
笔记:
请不要做#define true 1
和#define false 0
。它们与C的定义不同,因此如果您选择if (b == true)
而不是,可能会得到错误的结果if (b)
。
c
通常表示char
。i
(和j
和k
)更常用于索引。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句