在我之前的问题中,我打印了一个double using cout,当我没有预料到它时,它变得圆润了。我如何才能使cout打印一个双重使用全精度?
当前回答
你可以直接在std::cout上设置精度,并使用std::fixed格式说明符。
double d = 3.14159265358979;
cout.precision(17);
cout << "Pi: " << fixed << d << endl;
您可以#include <limits>来获得浮点数或双精度浮点数的最大精度。
#include <limits>
typedef std::numeric_limits< double > dbl;
double d = 3.14159265358979;
cout.precision(dbl::max_digits10);
cout << "Pi: " << d << endl;
其他回答
你可以直接在std::cout上设置精度,并使用std::fixed格式说明符。
double d = 3.14159265358979;
cout.precision(17);
cout << "Pi: " << fixed << d << endl;
您可以#include <limits>来获得浮点数或双精度浮点数的最大精度。
#include <limits>
typedef std::numeric_limits< double > dbl;
double d = 3.14159265358979;
cout.precision(dbl::max_digits10);
cout << "Pi: " << d << endl;
iostreams的方式有点笨拙。我更喜欢使用boost::lexical_cast,因为它为我计算了正确的精度。而且它也很快。
#include <string>
#include <boost/lexical_cast.hpp>
using boost::lexical_cast;
using std::string;
double d = 3.14159265358979;
cout << "Pi: " << lexical_cast<string>(d) << endl;
输出:
Pi: 3 . 14159265358979
以下是我会使用的方法:
std::cout << std::setprecision (std::numeric_limits<double>::digits10 + 1)
<< 3.14159265358979
<< std::endl;
基本上,限制包具有所有内置类型的特性。 浮点数(float/double/long double)的特征之一是digits10属性。这定义了以10为基底的浮点数的精度(我忘记了确切的术语)。
参见:http://www.cplusplus.com/reference/std/limits/numeric_limits.html 查看其他属性。
通过完全精度,我假设有足够的精度来显示与预期值的最佳近似值,但应该指出的是,double是使用以2为基数的表示来存储的,以2为基数不能准确地表示像1.1这样微不足道的东西。获得实际双精度(没有舍入错误)的唯一方法是打印出二进制位(或十六进制位)。
一种方法是使用并集将双精度值输入为整数,然后输出整数,因为整数不会受到截断或舍入问题的影响。(c++标准不支持这样的类型双关语,但C中支持。然而,大多数c++编译器可能无论如何都会打印出正确的值。我认为g++支持这一点。)
union {
double d;
uint64_t u64;
} x;
x.d = 1.1;
std::cout << std::hex << x.u64;
这将为您提供100%的精确精度的双…而且完全无法阅读,因为人类无法阅读IEEE双格式!维基百科上有一篇关于如何解释二进制位的很好的文章。
在较新的c++中,您可以这样做
std::cout << std::hexfloat << 1.1;
利用std::设置精度:
#include <iomanip>
std::cout << std::setprecision (15) << 3.14159265358979 << std::endl;