使用数组元素执行计算

时间:2021-02-13 13:06:30

I am trying to create a hashing function. The algorithm requires me to take each letter of the string and convert it to ASCII; multiply it by a number based on its position in the string (for example Input is STACK; ASCII for 'S' would be 344, multiply that value by 9^9 then ASCII for 'T' would be 347 multiply that value by 8^8.. etc); and then add the values together.

我正在尝试创建一个散列函数。该算法要求我取字符串的每个字母并将其转换为ASCII;将它乘以一个基于其在字符串中的位置的数字(例如,输入是STACK;'S'的ASCII将是344,将该值乘以9 ^ 9,然后'T'的ASCII将是347乘以该值8 ^ 8 ..等);然后将值一起添加。

I understand how to access the values in the array to create the sum and can convert them to ASCII. I don't understand how I would access the array to perform the calculations in-between.

我理解如何访问数组中的值来创建总和,并将它们转换为ASCII。我不明白我将如何访问数组以执行中间的计算。

I also get an "assertion failed error", when I build the program. I looked up the error and it says it has something to do with bad calls, however I can't see any bad calls in my code.

当我构建程序时,我也得到“断言失败错误”。我查了一下错误,它说它与坏的调用有关,但我在代码中看不到任何错误的调用。

my code is below :

我的代码如下:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string input ;
    int finalanswer = 0;

    cout << "Enter your first name please : " ;

    cin >> input;

    cout << "Your name is " << input ;

    for (int x=0; x=input.size(); x++)
    {   
        finalanswer += input[x];

        cout << finalanswer ;
    }

    cin.get();
    return 0;
}

1 个解决方案

#1


2  

The condition in the for-loop is wrong, it should be

for循环中的条件是错误的,它应该是

for(int x=0; x < input.size(); x++)

With your code, the second time the body of the loop is executed x is input.size() and that is too large to access input[x] - leading to the error you see.

使用你的代码,第二次执行循环体时x是input.size(),而且太大而无法访问输入[x] - 导致你看到的错误。


I'm not sure I understand the intended algorithm 100%, but that might help:

我不确定我100%理解预期的算法,但这可能会有所帮助:

int myPow(int x, int p)
{
  if (p == 0) return 1;
  if (p == 1) return x;
  return x * myPow(x, p-1);
}

and then for the loop:

然后为循环:

for(int x=0; x < input.size(); x++)
{
    finalanswer += input[x] * myPow(9-x);

    cout << finalanswer ;
}

#1


2  

The condition in the for-loop is wrong, it should be

for循环中的条件是错误的,它应该是

for(int x=0; x < input.size(); x++)

With your code, the second time the body of the loop is executed x is input.size() and that is too large to access input[x] - leading to the error you see.

使用你的代码,第二次执行循环体时x是input.size(),而且太大而无法访问输入[x] - 导致你看到的错误。


I'm not sure I understand the intended algorithm 100%, but that might help:

我不确定我100%理解预期的算法,但这可能会有所帮助:

int myPow(int x, int p)
{
  if (p == 0) return 1;
  if (p == 1) return x;
  return x * myPow(x, p-1);
}

and then for the loop:

然后为循环:

for(int x=0; x < input.size(); x++)
{
    finalanswer += input[x] * myPow(9-x);

    cout << finalanswer ;
}