gpt4 book ai didi

c++ - stringstream 在转换时失去精度

转载 作者:太空宇宙 更新时间:2023-11-04 16:06:42 24 4
gpt4 key购买 nike

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

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

输出是:44.23331002 = 44.2333

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

最佳答案

您需要在输出流上设置精度:

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

关于c++ - stringstream 在转换时失去精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34094915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com