gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:08:16 26 4
gpt4 key购买 nike

当使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com