[英]boost::lexical_cast and double — strange behavior
當我寫"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)並提升1.57。
提前致謝。
這是浮點不准確。
在二進制浮點中沒有精確的2.01表示,因此乘以100不會得到整數。
你可以看到它: Live On Coliru
std::cout << "double: " << std::setprecision(18) << std::fixed << b << '\n';
打印
double: 200.999999999999971578
因此,轉換為int失敗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.