我可以将std:fixed或std :: setprecision()与>>一起使用吗?操作员? [英] Can I use std:fixed or std::setprecision() with >> operator?

查看:92
本文介绍了我可以将std:fixed或std :: setprecision()与>>一起使用吗?操作员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: istringstream 失去精度.我可以使用类似于 std :: fixed std :: setprecision()的东西吗?

std::istringstream loses precision when converting a string to long double. Can I use something similar to std::fixed or std::setprecision()?

我正在使用c ++ 11并瞄准QNX平台.

I am using c++ 11 and targeting QNX platform.

#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 或流无关.

The issue you're having has nothing to do with your use of setprecision or streams.

80位双精度数( long double )不够大,无法以所需的精度存储您要存储的数字.80位双精度数的尾数为64位,这意味着它可以表示的数字精度与64位整数相同,后者本身被限制为19个十进制数字.您要存储的值是( 5.9486_57476_78615_88251_0631 )24个十进制数字,这意味着它太精确了,无法由程序准确表示.

An 80-bit double (long double) is not large enough to store the number you're trying to store with the precision you want. 80-bit doubles have a mantissa of 64 bits, meaning the precision of numbers it can represent is the same as a 64-bit integer, which itself is limited to 19 [decimal] digits of value. The value you're trying to store is (5.9486_57476_78615_88251_0631) 24 decimal digits of value, meaning it's simply too precise to be accurately represented by your program.

如果要将此值存储在程序中,则需要将其保留在其字符串表示形式中,或者找到一个任意的精度库来表示/操纵这些数字.我的建议是使用 boost.multiprecision 库,尽管它确实取决于您的组织/任务允许使用C ++ Boost库.

If you want to store this value in your program, you need to keep it in its string representation or find an arbitrary precision library for representing/manipulating these numbers. My recommendation is to use the boost.multiprecision library, though it does depend on your organization/task permitting use of the C++ Boost Libraries.

这篇关于我可以将std:fixed或std :: setprecision()与&gt;&gt;一起使用吗?操作员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆