2016-04-23 109 views
1

這裏:lexical_cast strtof strtold失去準確性?

#include <iostream> 
#include <cstdlib> 
#include <boost/lexical_cast.hpp> 

int main(void) { 
    const char * str = "277499.84"; 

    std::cout << boost::lexical_cast<double>(str) << std::endl; 
    std::cout << strtof(str, NULL) << std::endl; 
    std::cout << strtold(str, NULL) << std::endl; 
    std::cout << atof(str) << std::endl; 

    return 0; 
} 

輸出:

277500 
277500 
277500 
277500 

爲什麼輸出不277499.84?

+3

默認的精度是6我想,就像'printf'的'%f'一樣。改變它,如果你不喜歡它。 –

回答

3

這不是操作本身失去準確性,而是輸出

您可以使用I/O操縱器std::setprecision來控制數字精度。以下將使用double的完整精度(假定流設置爲十進制輸出)。可以使用std::ios_base::precision。如果您想在之後將精度恢復到原始值,這非常有用。

auto old_precision = cout.precision(std::numeric_limits<double>::digits10 + 1); 
cout << value; 
cout.precision(old_precision);