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


当前回答

利用std::设置精度:

#include <iomanip>
std::cout << std::setprecision (15) << 3.14159265358979 << std::endl;

其他回答

利用std::设置精度:

#include <iomanip>
std::cout << std::setprecision (15) << 3.14159265358979 << std::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 查看其他属性。

最轻松的……

#include <limits>

using std::numeric_limits;

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

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的作者。