功能中的添加不正确

Incorrect addition in a Function

本文关键字:不正确 添加 功能      更新时间:2023-10-16

我在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
}