c++ - 函数在许多数字上转换为基数 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++ 没有整数的 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');
}
推荐阅读
- powershell - 将powershell屏幕输出导出为图像
- linux - AWK 如何修改此代码,使其打印 num 个实例而不是 0 和 1
- python - 所有这些 python* 可执行文件是怎么回事?
- google-chrome - 带有 Selenium 的无头 Chrome 无法正确加载网页元素
- sql - 根据不同的分组条件计算总计
- excel - 将具有实际数据范围的所有工作表复制到新工作簿中,同时保留旧工作表名称
- javascript - 如何在 angular-material-table 中创建表单数组
- python - 如何在运行时使用python设置保存文件的路径?
- excel - 根据年份创建包含工作日和每月日期的表
- maven - java.lang.Exception:没有找到匹配 JUNIT 4 和 SpringBoot 的测试