c++ - 使用 lexical_cast<float>(string) 时会丢失精度

标签 c++ boost visual-studio-2013 floating-point lexical-cast

当使用 boost::lexical_cast(我在 VS2013 上使用 boost 版本 1.58)时,我无法获得字符串中指定的确切值,即使它可以用 float 表示:

std::wstring t = L"91.25";
float r;
r = boost::lexical_cast<float>(t);

r 是 91.249992 (0x42B67FFF) 而不是 91.250000 (0x42b68000)

以前版本的 boost 以预期的方式运行。我是否缺少精确设置?

最佳答案

事实证明这与 boost 无关。这似乎是 Visual Studio 和 VS2013 的问题。

#include <iostream>
#include <sstream>
#include <iomanip>
int main()
{
    float a;
    std::stringstream s;
    s.str("91.25");
    s >> a;
    std::wcout << std::setprecision(20) << a << std::endl;
    // displays "91.249992370605469" when compiled with 
    // VS2013 and "91.25" when compiled with VS2010 or VS2015
    return 0;
}

关于c++ - 使用 lexical_cast<float>(string) 时会丢失精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37995387/

相关文章:

c++ - 如何检测隐藏进程

c++ - 在没有 std 和 std::strings 的情况下以 printf 方式创建 QString

c++ - 如何使用 boost::date_time 在本地时间和世界时间之间进行转换?

boost tcp 客户端有时无法检测到与服务器的断开连接

c# - VS 2013 C# 和 Git : . csproj 文件在 pull 时不 merge

c++ - cin 和赋值的区别

c++ - 数组结构

c++ - 使用 BOOST.python 将结构从 C++ 返回到 Python

c++ - 如果 (cin >> number_1) 不起作用

c# - Visual Studio 在运行时找不到 .dll