在我之前的问题中,我打印了一个double using cout,当我没有预料到它时,它变得圆润了。我如何才能使cout打印一个双重使用全精度?


当前回答

上ostream::精密(int)

cout.precision( numeric_limits<double>::digits10 + 1);
cout << M_PI << ", " << M_E << endl;

将产生

3.141592653589793, 2.718281828459045

为什么说“+1”我不知道,但你多出来的数字是正确的。

其他回答

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

在c++ 20中,你可以使用std::format来做到这一点:

std::cout << std::format("{}", M_PI);

输出(假设双IEEE754):

3.141592653589793

默认浮点格式是具有往返保证的最短十进制表示形式。与setprecision I/O操纵符相比,这种方法的优点是它不会打印不必要的数字。

在此期间,您可以使用{fmt}库,std::format是基于。{fmt}还提供了print函数,使这更容易和更有效(godbolt):

fmt::print("{}", M_PI);

免责声明:我是{fmt}和c++ 20 std::format的作者。

最轻松的……

#include <limits>

using std::numeric_limits;

    ...
    cout.precision(numeric_limits<double>::digits10 + 1);
    cout << d;

你可以直接在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::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 查看其他属性。