Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/145.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 指数pow函数返回错误的ASCII总计_C++_Algorithm_Ascii_Pow - Fatal编程技术网

C++ 指数pow函数返回错误的ASCII总计

C++ 指数pow函数返回错误的ASCII总计,c++,algorithm,ascii,pow,C++,Algorithm,Ascii,Pow,我正在做一个函数,将字符串转换为编码为基数31的数字。比如说, "cat" => 'c' * 31^(3-1) + 'a' * 31^(3-2) + 't' = 67510 我的代码打印如下: Enter text to convert to ASCII: cat ASCII : 99 ASCII : 97 ASCII : 116 ASCII total: 312 Each ASCII in algorithm : 95139 Each ASCII in algorithm : 9

我正在做一个函数,将字符串转换为编码为基数31的数字。比如说,

"cat"  =>  'c' * 31^(3-1) + 'a' * 31^(3-2) + 't'  = 67510
我的代码打印如下:

Enter text to convert to ASCII: cat
ASCII : 99
ASCII : 97
ASCII : 116
ASCII total: 312
Each ASCII in algorithm : 95139
Each ASCII in algorithm : 98146
Each ASCII in algorithm : 98146
Total ASCII algorithm : 98262
换言之:

'c' should be 95139
'a' should be 3007
't' should be 116
我相信这个问题是在我的pow功能中发现的,但是从我引用的例子来看,我的设置应该是有效的。我似乎无法确定是什么导致了这个问题,我想看看第二双眼睛是否能帮助我看到这个问题

代码:


长度+增量不应该是-而不是+?@Kolmar是的,我刚在发布后发现了这个问题,所以我纠正了这个问题。但是,assci值仍然是错误的。cat的值“a”应为“3007”,如果c应为95139,则cat->67510没有意义。您正在打印num,这是所有先前值的总和,因此对于a,程序实际上是打印a和cNormally的值的总和,当您谈论基数b时,数字是0到b-1。如果只输入不带标点符号的小写单词,则允许从int'a'=97到int'z'的数字。更常见的是从每个字母的值中减去int'a'。
#include <iostream>
#include <string>
#include <math.h>
using namespace std;

void ToASCII(string letter)
{
    int total =0;
    int length = 0;
    int increment = 1;
    int num =0;
    for (int i = 0; i < letter.length(); i++)
    {
        char x = letter.at(i);
        cout <<"ASCII : "<< int(x) << endl;
        total = total + x;
        length++;
    }
    cout <<"ASCII total: "<< total << endl;
    int code = 0;
    for (int j = 0; j < length; j++){

        num += int(letter.at(j))* pow(31,(length-increment));
        cout <<"Each ASCII in algorithm : " << num <<endl;
        increment++;
    }
    cout <<"Total ASCII algorithm : " << num<<endl;
}

int main()
{
    string Text;
    cout << "Enter text to convert to ASCII: ";
    getline(cin, Text);
    ToASCII(Text);
    return 0;
}