boost :: lexical_cast和双重奇怪的行为

Fro*_*art 5 c++ boost

为什么以下代码在我写"2.01"和时给出了不同的结果"2.02"

#include <boost/lexical_cast.hpp>

#include <iostream>
#include <string>

int main()
{
  const std::string str = "2.02";

  try
  {
    const double b = boost::lexical_cast<double>(str) * 100.0;
    std::cout << "double: " << b << '\n';
    const int a = boost::lexical_cast<int>(b);
    std::cout << "int: " << a << '\n';
  }
  catch (const std::exception& ex)
  {
    std::cerr << ex.what() << '\n';
  }
}
Run Code Online (Sandbox Code Playgroud)

产量

double: 202
int: 202
Run Code Online (Sandbox Code Playgroud)

但是,如果我改变"2.02""2.01"它给了我下面的输出:

double: 201
bad lexical cast: source type value could not be interpreted as target
Run Code Online (Sandbox Code Playgroud)

为什么?

我正在使用Visual Studio 2013(msvc-12.0)并提升1.57.

提前致谢.

seh*_*ehe 2

这是浮点不准确。

2.01没有二进制浮点数的精确表示,因此乘以 100 不会得到整数。

您可以使其可见:Live On Coliru

std::cout << "double: " << std::setprecision(18) << std::fixed << b << '\n';
Run Code Online (Sandbox Code Playgroud)

印刷

double: 200.999999999999971578
Run Code Online (Sandbox Code Playgroud)

由于这个原因,转换为 int 失败。