stringstream 在转换时失去精度

stringstream loses precision while converting

我对 stringstream 有一个小问题。当我用它将字符串转换为双精度时它会失去精度。

const std::string str = "44.23331002";
double x;
stringstream ss;
ss << str;
ss >> x;
cout << str << " = " << x << endl;

输出为: 44.23331002 = 44.2333

这是为什么?它是否转换为浮点数并且数字精度有限?

您需要设置输出流的精度:

#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;

int main() {
    const std::string str = "44.23331002";
    double x;
    stringstream ss;
    ss << str;
    ss >> x;
    cout << str << " = " << std::setprecision(10) << x << endl;
}

输出:

44.23331002 = 44.23331002

(Demo)

calcto 回答 correctly.and 您可以通过两种方式更改精度: std::setprecision(10)std::cout.precision(10)