gpt4 book ai didi

c++ - boost::lexical_cast 和 double——奇怪的行为

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:43:50 25 4
gpt4 key购买 nike

为什么当我写 "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';
}
}

输出

double: 202
int: 202

但是如果我将 "2.02" 更改为 "2.01" 它会给我以下输出:

double: 201
bad lexical cast: source type value could not be interpreted as target

为什么?

我正在使用 Visual Studio 2013 (msvc-12.0) 和 boost 1.57。

提前致谢。

最佳答案

这是 float 不准确。

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

你可以让它可见: Live On Coliru

std::cout << "double: " << std::setprecision(18) << std::fixed << b << '\n';

打印

double: 200.999999999999971578

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

关于c++ - boost::lexical_cast 和 double——奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28366401/

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