Thi*_*ame 1 c++ precision stringstream
我对字符串流有一个小问题。当我用它将字符串转换为双精度时,它会失去精度。
const std::string str = "44.23331002";
double x;
stringstream ss;
ss << str;
ss >> x;
cout << str << " = " << x << endl;
Run Code Online (Sandbox Code Playgroud)
输出为: 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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
44.23331002 = 44.23331002
Run Code Online (Sandbox Code Playgroud)