将字符串转换为双精度时出现算术错误

Arithmetic Error When Converting String to Double

我正在编写一个函数,将用户提供的字符串转换为双精度数。它对某些值非常有效,但对其他值却失败了。例如

string_to_double("123.45") = 123.45
string_to_double(12345) = 12345

但是

string_to_double(123.4567) = 123.457

我相当确定这是某种舍入误差,但我没有使用近似值,也没有使用非常小或大的值。我的问题有两个方面,为什么我会得到这些奇怪的结果,以及如何更改我的代码以获得更准确的结果?我这样做也是个人挑战,因此使用 std::stod 等方法的建议没有帮助。我相信问题出现在第二个 for 循环中,但我觉得包含整个方法是明智的,因为如果我遗漏了什么,也不需要阅读那么多额外的代码。

我的代码

template <class T>
double numerical_descriptive_measures<T>::string_to_double(std::string user_input)
{
    double numeric_value = 0;//Stores numeric value of string. Return value.
    int user_input_size = user_input.size();
    int power = 0;
    /*This loop is for the characteristic portion of the input
    once this loop finishes, we know what to multiply the
    characterstic portion by(e.g. 1234 = 1*10^3 + 2*10^2 + 3*10^1 + 4)
    */
    for(int i = 0;i < user_input_size;i++)
    {
        if(user_input[i] == '.')
            break;
        else
            power++;
    }
    /*This loop is for the mantissa. If this portion is zero, 
    the loop doesn't execute because i will be greater than
    user_input_size.*/
    for(int i = 0;i < user_input_size;i++)
    {
        if(user_input[i] != '.')
        {
            numeric_value += ((double)user_input[i] - 48.0)*pow(10,power-i-1);
        }
        else
        {
            double power = -1.0;
            for(int j = i+1;j < user_input_size;j++)
            {
                numeric_value += ((double)user_input[j] - 48.0)*pow(10.0,power);
                power = power-1.0;
            }
            break;
        }
    }
    return numeric_value;
}

问题不是您生成了错误的浮点值,而是您打印的精度不够:

std::cout<<data<<std::endl

这只会打印大约六位精度。您可以使用std::setprecision或其他方法打印更多。

您的代码没有为“123.4567”生成不正确的值,但通常会生成不正确的值。例如,string_to_double("0.0012") 产生(在 Visual Studio 2015 年)

0.0012000000000000001117161918529063768801279366016387939453125

但正确答案是

0.00119999999999999989487575735580549007863737642765045166015625

(您必须将它们打印到 17 位有效数字才能区分。)

问题是您不能使用浮点数转换为浮点数 -- 通常它没有足够的精度。

(我在我的网站上写了很多关于此的内容;例如,请参阅 http://www.exploringbinary.com/quick-and-dirty-decimal-to-floating-point-conversion/ and http://www.exploringbinary.com/decimal-to-floating-point-needs-arbitrary-precision/。)