我很好奇问题是否是我需要不同的哈希函数或者我的代码是否有问题。我需要对单词进行哈希处理以存储在哈希表中,该函数似乎一切正常,但是当我输入很长的单词时,有些单词是 45 个字符,即使我要求返回一个 unsigned long long对我来说,我收到的哈希值是负数。
这是代码,非常感谢您的帮助。
unsigned long long hash(char* str);
int main (void)
{
int numItems;
char name[46];
printf("Please enter how many items will be in your hashtable:");
scanf("%d", &numItems);
for (int i = 0; i < numItems; i++)
{
int key = 0;
printf("Please type a name to be entered into the Hashtable:");
scanf("%s", name);
//run the word through a hashfunction (simple hashfunction)
//print the hash number
key = hash(name);
printf("%d\n", key);
}
}
unsigned long long hash(char* str)
{
unsigned long hash = 5381;
int c;
for (int i = 0; i < strlen(str); ++i)
{
c = (int) str[i];
hash = ((hash << 5) + hash) + c;
}
return hash;
}
最佳答案
hash
函数返回一个 unsigned long long
,但您将结果存储在 int
中。
将key
类型更改为unsigned long long
,并使用%llu
格式说明符打印它。
unsigned long long key = 0;
....
printf("%llu\n", key);
此外,hash
函数内的 hash
变量应具有类型 unsigned long long
,并且应重命名该变量,以免与函数名称冲突。
关于c - C 中的哈希函数给出负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39981175/