我可以将 std:fixed 或 std::set precision() 与 >> 运算符一起使用吗?

2024-03-15

std::istringstream将字符串转换为 long double 时会丢失精度。我可以使用类似的东西吗std::fixed or 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

您遇到的问题与您的使用无关setprecision或溪流。

80 位双精度 (long double) 不够大,无法以您想要的精度存储您尝试存储的数字。 80 位双精度数的尾数为 64 位,这意味着它可以表示的数字精度与 64 位整数相同,而 64 位整数本身仅限于 19 位数字。您尝试存储的值是(5.9486_57476_78615_88251_0631) 24 位十进制数字的值,这意味着它太精确,无法由您的程序准确表示。

如果您想在程序中存储这个值,您需要将其保留在字符串表示形式中,或者找到一个任意精度的库来表示/操作这些数字。我的建议是使用增强多精度 https://www.boost.org/doc/libs/1_69_0/libs/multiprecision/doc/html/index.html库,尽管它确实取决于您的组织/任务是否允许使用 C++ Boost 库。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我可以将 std:fixed 或 std::set precision() 与 >> 运算符一起使用吗? 的相关文章

随机推荐