程序提示用户输入存储在两个不同数组中的两个单词。 如果这些单词是字谜词,它会打印“Anagram”,如果不是,它会打印“Not Anagram”。我为所有字母表字母创建了一个数组,字母“a”存储为 {1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ...} 填充整个字母数组。
然后我比较了两个数组,以确定它们是否是同一个单词,我减去了每个字母,如果它们是 0(相互抵消),那么它们就是字谜词。 到目前为止,这是我的代码,我不确定我做错了什么。我很确定 bool 函数有问题。
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
void read_word(int counts[26])
{
int i;
char ch;
printf("Enter a word: ");
for(i=0;(ch=getchar()) != '\n' && i<30; i++)
counts[toupper(ch)-'A']++;
}
bool equal_array(int counts1[26],int counts2[26])
{
int i;
bool is_anagram=false;
for(i=0; i<30; i++)
{
counts1[i]= counts1[i] - counts2[i];
if(counts1[i] == 0)
{
is_anagram=true;
}
else
{
is_anagram=false;
break;
}
}
return is_anagram;
}
int main()
{
int first_word[26]={0};
int second_word[26]={0};
read_word(first_word);
read_word(second_word);
if( equal_array(first_word,second_word) == true)
printf("Anagram");
else
printf("Not Anagram");
return 0;
}
如果我能得到任何帮助,我将不胜感激。
最佳答案
bool equal_array(int counts1[26],int counts2[26])
...
for(i=0; i<30; i++)
意味着您最终将比较数组的第 27 到 30 个元素与仅 26 个元素。这是(1)未定义的行为,(2)一个明显的错误,以及(3)如果它不崩溃并烧毁,可能会产生错误的结果。
<小时/>我也不明白为什么你的读取循环中有 30 个字符的限制。您不会将单词存储在任何地方,因此没有理由任意限制它们的长度。另一方面,您不会检查字母实际上是否在 A
..Z
范围内,因此如果用户输入非字母字符,您的函数将修改计数数组范围之外的一些随机字节,导致未定义的行为,如上所述。
最后写得短一点:
bool equal_array(int counts1[26],int counts2[26]) {
int i;
for(i=0; i<26; i++) {
if(counts1[i] != counts2[i]) return false;
}
return true;
}
有些人不喜欢像这样的循环中间的返回,所以如果你的教授是其中之一,我想你将需要 bool 变量。但我个人觉得上面的版本更容易阅读。
关于C 程序查找两个单词是否是字谜(我的代码在里面),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38680751/