2015-02-06 79 views
5

爲什麼下面的代碼在寫"2.01""2.02"時給了我不同的結果?boost :: lexical_cast和雙重奇怪行爲

#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。

在此先感謝。

回答

2

這是浮點不準確。

沒有確切表示二進制浮點2.01所以乘以100不會導致整數。

可以使其可見:Live On Coliru

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

打印

double: 200.999999999999971578 

轉換爲INT失敗,因爲這個原因。

+0

解決的辦法是先將它加倍,然後再加上,對吧? – rubikonx9 2015-02-06 13:07:49

+1

'lexical_cast'可以像OP代碼一樣用於數值轉換嗎?它不是隻爲轉換爲字符串類型的轉換嗎? – 2015-02-06 13:09:39

+1

@ g.tsh否。解決方法是使用十進制表示或整數運算。不要忘記,小數表示仍然有精度限制(如10/3 = 3.333333 ...) – sehe 2015-02-06 13:09:39