2016-04-23 108 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);