我正在尝试从我的C ++书中处理以下编程练习:“编写一个函数,它接受一个字符串作为参数并返回一个原始的哈希码,它是通过添加所有字符的值来计算的。字符串。“
我的解决方案是:
#include <iostream>
#include <string>
#define clrscr() system("cls")
#define pause() system("pause")
using namespace std;
int hashc(char string[]);
int main()
{
char phrase[256];
cout << "This program converts any string into primitve hash-code." << "\n";
cout << "Input phrase: "; cin.getline(phrase, sizeof(phrase));
cout << "\n";
cout << "Hash-code for your phrase is: " << hashc(phrase) << "\n\n";
pause();
return(0);
}
int hashc(char string[])
{
int index;
int length;
int hash_value = 0;
length = strlen(string);
for(index = 0; index >= length; ++index)
{
hash_value = hash_value + string[index];
}
return(hash_value);
}
问题是:函数总是返回hash_value = 0
,因为它似乎正在跳过for循环。当我在函数中返回length
时,它会返回给定字符串的正确长度(index >= length
为index = 0
)。因此它通常应该触发for循环,不应该吗?在这里有点提示非常感谢!
干杯!
答案 0 :(得分:2)
惯用的for循环应该如下所示:
for(index = 0; index < length; ++index)
{
hash_value += string[index];
}
主要特征是索引从0(index = 0
)开始,索引与'less-than'(index < length
)的长度进行比较,并且正如您所拥有的那样,索引使用预增量(++index
)递增。
答案 1 :(得分:1)
for(index = 0; index < length; ++index)
此刻你永远不会进入循环,没有任何字符导致我的系统出现分段错误。它在唯一的情况下进入循环,它通过条件(length >= index
,即0> = 0),然后循环,直到它试图访问非法位置,此时发生seg错误。