我可以将 std:fixed 或 std::setprecision() 与 >> 运算符一起使用吗?
Can I use std:fixed or std::setprecision() with >> operator?
std::istringstream
在将字符串转换为 long double 时会丢失精度。我可以使用类似于 std::fixed
或 std::setprecision()
的东西吗?
我正在使用 c++ 11 并面向 QNX 平台。
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
int main(){
long double convertedNumber;
std::string numberString ("5.94865747678615882510631e+4931");
//From string to long double
std::istringstream iss(numberString);
iss >> convertedNumber;
std::cout<< std::setprecision(30) << numberString << "\n";
std::cout<< std::setprecision(30) << convertedNumber << "\n";
return 0;
}
输出为
5.94865747678615882510631e+4931
5.9486574767861588254e+4931
是的,它会起作用,这些是用于任何流的函数。
流是用于接收和发送字节的 construct
流使用
<< Insertion operator
And the >> extraction operator
std::setprecision 函数是一个 stream manipulator
可以应用于任何流
编辑
如果你的问题是为什么它的精度不是 30,那是因为你在做
时失去了精度
iss >> convertedNumber;
并且iss流是根据您输入的最精确的数字。
坚持 Xirema 的回答,以获得更技术性的解释和解决方案
您遇到的问题与您使用 setprecision
或流无关。
80 位双精度数 (long double
) 不够大,无法以您想要的精度存储您要存储的数字。 80 位双精度数的尾数为 64 位,这意味着它可以表示的数字精度与 64 位整数相同,64 位整数本身限制为 19 [decimal] 位的值。您尝试存储的值是 (5.9486_57476_78615_88251_0631
) 24 个十进制数字,这意味着它太精确了,无法由您的程序准确表示。
如果你想在你的程序中存储这个值,你需要将它保存在它的字符串表示中,或者为 representing/manipulating 这些数字找到一个任意精度的库。我的建议是使用 boost.multiprecision 库,尽管它确实取决于您 organization/task 是否允许使用 C++ Boost 库。
std::istringstream
在将字符串转换为 long double 时会丢失精度。我可以使用类似于 std::fixed
或 std::setprecision()
的东西吗?
我正在使用 c++ 11 并面向 QNX 平台。
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
int main(){
long double convertedNumber;
std::string numberString ("5.94865747678615882510631e+4931");
//From string to long double
std::istringstream iss(numberString);
iss >> convertedNumber;
std::cout<< std::setprecision(30) << numberString << "\n";
std::cout<< std::setprecision(30) << convertedNumber << "\n";
return 0;
}
输出为
5.94865747678615882510631e+4931
5.9486574767861588254e+4931
是的,它会起作用,这些是用于任何流的函数。 流是用于接收和发送字节的 construct 流使用
<< Insertion operator
And the >> extraction operator
std::setprecision 函数是一个 stream manipulator 可以应用于任何流 编辑 如果你的问题是为什么它的精度不是 30,那是因为你在做
时失去了精度iss >> convertedNumber;
并且iss流是根据您输入的最精确的数字。 坚持 Xirema 的回答,以获得更技术性的解释和解决方案
您遇到的问题与您使用 setprecision
或流无关。
80 位双精度数 (long double
) 不够大,无法以您想要的精度存储您要存储的数字。 80 位双精度数的尾数为 64 位,这意味着它可以表示的数字精度与 64 位整数相同,64 位整数本身限制为 19 [decimal] 位的值。您尝试存储的值是 (5.9486_57476_78615_88251_0631
) 24 个十进制数字,这意味着它太精确了,无法由您的程序准确表示。
如果你想在你的程序中存储这个值,你需要将它保存在它的字符串表示中,或者为 representing/manipulating 这些数字找到一个任意精度的库。我的建议是使用 boost.multiprecision 库,尽管它确实取决于您 organization/task 是否允许使用 C++ Boost 库。