【问题标题】:CS50 Speller handles most basic words properlyCS50 Speller 可以正确处理最基本的单词
【发布时间】:2020-06-05 04:02:20
【问题描述】:

大家好,我正在做 CS50 的拼写练习,我遇到了这个错误。

正确处理最基本的单词

完整的错误信息是:

running ./speller basic/dict basic/text...
checking for output "MISSPELLED WORDS\n\n\nWORDS MISSPELLED: 0\nWORDS IN DICTIONARY: 8\nWORDS IN TEXT: 9\n"...

Expected Output:
MISSPELLED WORDS


WORDS MISSPELLED:     0
WORDS IN DICTIONARY:  8
WORDS IN TEXT:        9
Actual Output:
MISSPELLED WORDS

over

WORDS MISSPELLED:     1
WORDS IN DICTIONARY:  8
WORDS IN TEXT:        9

这是我的检查功能:

// Implements a dictionary's functionality
#include <strings.h>
#include <stdbool.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "dictionary.h"


// Represents a node in a hash table
typedef struct node
{
    char word[LENGTH + 1];
    struct node *next;
}
node;


// Number of buckets in hash table
const unsigned int N = 27;

int word_count;

char dictionary_word[LENGTH + 1];
// Hash table
node *table[N];

// Returns true if word is in dictionary else false
bool check(const char *word)
{
    // TODO
    unsigned int word_pos = hash(word);

    node *cursor = table[word_pos];

    while (cursor != NULL)
    {
        if ((strcasecmp(cursor->word, word)) == 0)
        {
            return true;
        }
        else
        {
            cursor = cursor->next;
        }
    }
    return false;
}

哈希函数:

unsigned int hash(const char *word) 
{ 
 int index = 0; 
 for (int i = 0; word[i] != '\0' ; i++) 
 { 
   index += tolower(word[i]); 
 } 
 return index % N ; 
} 

非常感谢一些指导,我不是 C 专家,所以我希望得到深入的解释,因为我期待尽可能多地学习。

谢谢!

【问题讨论】:

  • 检查功能在我看来没问题。你能添加你的哈希函数吗?每当您使用指针时,请先初始化它们!否则,您不知道该指针指向的位置..您可能会遇到分段错误..
  • 这里是: unsigned int hash(const char *word) { int index = 0 ; for (int i = 0 ; word[i] != '\0' ; i++) { index += tolower(word[i]) ; } 返回索引 % N ; }
  • 任何被错误初始化的指针? @earik87
  • 你能在代码 sn-p 中为你的问题添加哈希函数吗?
  • @earik87 将哈希函数添加到问题中。

标签: c cs50


【解决方案1】:

只是更改了哈希函数并工作。

哈希函数:

// Hashes word to a number
unsigned int hash(const char *word)
{
    int index = 0 ;
    for (int i = 0 ; word[i] != '\0' ; i++)
    {
        index += tolower(word[i]) ;
    }
    return index % N ;
}

并将N的值更改为:65536

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    • 1970-01-01
    • 2022-01-15
    相关资源
    最近更新 更多