我已经在这个程序上连续工作了 5 天,但不明白为什么它会这样。谢谢你帮我。
文件speller.c中有代码调用了文件dictionary.c中的4个函数
在speller.c中,它调用了某个函数:
bool misspelled = !check(word);
如果 misspelled 为 false,则表示检查函数返回 true。
这是 dictionary.c 中的检查函数:
bool check(const char *word)
{
int key = hash(word);
printf("Word: %s position: %i\n", word, key);
node* trav = dictArray[key];
while (trav != NULL)
{
if(trav->word == word)
printf("%s found in the dictionary\n", word);
return true;
trav = trav->next;
}
printf("%s NOT found in the dictionary\n", word);
return false;
Check() 如果可以在哈希表中找到作为参数传递的单词,它将检查哈希表,并打印每个单词及其键。如果找到它,它会打印一条消息并返回 true
。如果不是,则打印一条消息,并返回 false
。
哈希表是一个包含 26 个元素的数组,每个元素都是一个包含 2 个元素的结构,一个是字符串,另一个是指向列表中下一个结构(节点)的指针。
根据单词的第一个字母将节点添加到列表中。
问题是我已经测试了添加到数组中的每个单词,即使单词不存在,函数仍然返回 true
。
事实上,对于作为参数传递的每个单词,它都会返回 true
。
现在真正令人费解的行为是 check() 必须在返回 true
或 false
之前向屏幕打印一些内容。 ...found ...
或 ... NOT found ...
。
好吧,事实并非如此。但它仍然返回“真”,这让我很困惑。
有什么帮助吗? 我应该从两个文件中粘贴整个代码吗?
最佳答案
仔细观察:
while (trav != NULL)
{
if(trav->word == word)
printf("%s found in the dictionary\n", word);
return true;
trav = trav->next;
}
if
block 周围没有大括号。因此,通过适当的缩进,您真正拥有的是:
while (trav != NULL)
{
if(trav->word == word)
printf("%s found in the dictionary\n", word);
return true;
trav = trav->next;
}
所以你总是在第一次循环迭代时返回 true。
此外,您不想使用 ==
来比较字符串。您最终要做的是比较指针值,这几乎总是不相等的。使用 strcmp
来比较字符串。
固定代码:
while (trav != NULL)
{
if(!strcmp(trav->word, word)) {
printf("%s found in the dictionary\n", word);
return true;
}
trav = trav->next;
}
关于c - Bool 函数在不满足条件的情况下返回 true - 忽略 printf(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52068727/