功能中的添加不正确
Incorrect addition in a Function
我在C 中编写一个函数,以将数字从某些基数转换为十进制。当数字的数量均匀时,它可以正常工作,但是当它很奇怪时,它给出了错误的答案。
例如:
Number to convert : 100
Base to convert to: 10
Correct answer : 100
Function's output : 99
这是代码:
unsigned long long convertToDecimal(const std::string& number, const unsigned base)
{
std::string characters = "0123456789abcdef";
unsigned long long res = 0;
for(int i = 0, len = number.size(); i<len; ++i)
{
res += characters.find(number.at(i))*std::pow(base, len-1-i);
}
return res;
}
我正在使用G C 11。
我无法重现您的特定问题,但是std::pow
返回浮点数,您的实现可能已经引入了某种舍入错误,这导致了错误的结果,当转换为 unsigned long long
时,导致了错误的结果。<<<<<<<<<<<<<<<<<<。/p>
要避免这些错误,在处理整数时,您应该考虑避免std::pow
。例如,您的功能本可以是这样写的:
#include <iostream>
#include <string>
#include <cmath>
unsigned long long convertToDecimal(const std::string& number, const unsigned base)
{
std::string characters = "0123456789abcdef";
unsigned long long res = 0;
unsigned long long power = 1;
for(auto i = number.crbegin(); i != number.crend(); ++i)
{
// As in your code, I'm not checking for erroneous input
res += characters.find(*i) * power;
power *= base;
}
return res;
}
int main ()
{
std::cout << convertToDecimal("100", 2) << 'n'; // --> 4
std::cout << convertToDecimal("1234", 8) << 'n'; // --> 668
std::cout << convertToDecimal("99999", 10) << 'n'; // --> 99999
std::cout << convertToDecimal("fedcba", 16) << 'n'; // --> 16702650
}
相关文章:
- 使用2个键的cpp-stl::优先级队列排序不正确
- 正弦级数方程计算不正确
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 密码登录程序将永远循环并显示不正确的结果
- 在C++中返回不正确的楼层函数值
- 形状对象的旋转和缩放不正确C++
- C++ 读取文件读取文件不正确
- 关于类的 Python 文档 - 对C++的引用不正确
- 特征 LLT 模块给出不正确的结果?
- glibcxx STL 在实现 std::valarray::sum() 时是否不正确?
- 如果语句逻辑不正确
- 来自逆 vp 矩阵和相机位置的光线方向不正确
- 不正确的操作数类型 MSVC
- 数组填充了不正确的值
- 我是否不正确地集中了这些字符数组?
- 为什么除非我使用 cout,否则我的值不正确?
- 计算幂级数的数学结果不正确
- 为什么 sizeof 在 C++ 中给出不正确的字节数?
- 功能中的添加不正确
- gtkmm菜单栏不可见或未正确添加到网格