当我通过“冰”时,这应该返回451,845,518,507但是它返回873,952,427可以有人告诉我为什么吗? (MAX_STR_SIZE = 501)
unsigned long hash_code(const char *str){
char temp[MAX_STR_SIZE]="";
unsigned long multiplied;
if(str == NULL){
return SUCCESS;
}
else if(strlen(str)==0 || str==""){
return SUCCESS;
}
else{
strncpy(temp,str, strlen(str)-1);
temp[strlen(str)-1]=0;
multiplied = (hash_code(temp)*65599 + (int) str[strlen(str)-1]);
return multiplied;
}
}
答案 0 :(得分:5)
unsigned long
在您的计算机上只有32位。需要更广泛的类型451,845,518,507
451,845,518,507 mod pow(2,32) --> 873,952,427
答案 1 :(得分:1)
这是固定代码:
#include <stdio.h>
#include <string.h>
#define MAX_STR_SIZE 501
unsigned long long hash_code(const char *str){
char temp[MAX_STR_SIZE] = "";
unsigned long long hash;
if(str == NULL || strlen(str) == 0 || *str == '\0'){
return 0;
}
else{
strncpy(temp, str, strlen(str) - 1);
hash = hash_code(temp) * 65599 + str[strlen(str) - 1];
return hash;
}
}
int main(void)
{
char str[] = "ice";
unsigned long long hash;
hash = hash_code(str);
printf("%llu", hash);
return 0;
}
您需要unsigned long long
来包含451,845,518,507
。