【发布时间】:2013-12-22 22:12:24
【问题描述】:
我正在尝试处理我的 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 = 0,它是index >= length)。因此它通常应该触发for循环,不是吗?非常感谢这里的一点提示!
干杯!
【问题讨论】:
-
如何为std::hash 使用适当的专业化??
-
是的,这可能是正常的处理方式。我在我的 C++ 基础书籍的第 9 章,这是关于传递参数和返回值的。我认为重点是用我目前学到的东西来解决这些任务。
-
在
for (a;b;c)中,表达式b需要为true才能执行循环迭代,它应该产生false来终止循环。看来你搞反了。
标签: c++ for-loop parameter-passing return-value hashcode