我正在尝试将“ 21898.99”转换为字符串,但是我继续获取21898.990000000002,但是我期望21898.99
#include <cstdlib>
#include <boost/lexical_cast.hpp>
#include <limits>
#include <iostream>
int main()
{
double d1 = std::strtod("21898.99", nullptr);
long double d2 = std::strtold("21898.99", nullptr);
float d3 = std::strtof("21898.99", nullptr);
double d4 = atof("21898.99");
double d5 = boost::lexical_cast<double>("21898.99");
double d6;
sscanf_s("21898.99", "%lf", &d6);
double d7;
sscanf_s("21898.99", "%lg", &d7);
std::istringstream ss("21898.99");
double d8 = 0.0;
ss >> d8;
typedef std::numeric_limits< double > dbl;
std::cout.precision(dbl::max_digits10);
std::cout << d1 << "\n";
std::cout << d2 << "\n";
std::cout << d3 << "\n";
std::cout << d4 << "\n";
std::cout << d5 << "\n";
std::cout << d6 << "\n";
std::cout << d7 << "\n";
std::cout << d8 << "\n";
}
输出:
21898.990000000002
21898.990000000002
21898.990234375
21898.990000000002
21898.990000000002
21898.990000000002
21898.990000000002
21898.990000000002
Windows 10版本10.0.14939.0
Visual Studio 2017 15.9.0,C ++ 19.15.26732.1
Windows SDK 10.0.17134.0
我在使用gcc的centos机器上进行了尝试,此调用有效,但其他调用也失败了。
长双倍d2 = std :: strtold(“ 21898.99”,nullptr);
因为它返回21898.99
答案 0 :(得分:1)
这是浮点数的预期行为;有些值不能精确表示。