首页 > 解决方案 > 函数在许多数字上转换为基数 2 时减去 1?

问题描述

在我的代码中,我有命令行参数,并且它们被正确传递。我正在使用系数基指数形式将基数 2-10 转换为基数 10。它适用于许多数字,但许多其他数字不起作用。将基数为 10 的数字(3 位数字)转换为基数 10 是很明显的。

这是我的功能:

int decimal(int inbase, int dig, int argc, char *argv[])
{

    int total = 0, place = dig - 1;

    for(int i = 0; i < dig; i++)
    {
        total = total + (argv[2][place] - '0')*pow(inbase, i);
        cout<<"Argv: "<<argv[2][place] - '0'<<endl;
        cout<<"Power: "<<pow(inbase, i)<<endl;
        cout<<"Total After: "<<total<<endl;
        place--;
    }

    return total;
}

Argv[2] 作为字符串传递,编译此程序时的示例输入为:./a.exe 10 100 10 以 10 为底的预期输出:100 我得到的结果:99

标签: c++

解决方案


C++ 没有整数的 pow:https ://en.cppreference.com/w/cpp/numeric/math/pow

您可能在所有浮点/整数转换中的某个地方丢失了数据。

另外,简单地说:

int total = 0;
for (int i = 0; i < len; ++i) {
    total = total * base + arr[i];
}

或者,使用您拥有的变量:

int total = 0;
for (int i = 0; i < dig; ++i) {
    total = total * inbase + int(argv[2][i] - '0');
}

推荐阅读