📜  c++中的long pi(1)

📅  最后修改于: 2023-12-03 14:59:50.481000             🧑  作者: Mango

C++中的long pi

在C++中,long double是可以存储比double更长的有理数的数据类型。而pi是一个无理数,它的精确值无法存储在计算机内存中。

但是,我们可以使用数学库中提供的常数来获取pi的近似值。例如,在C++的数学库cmath中,我们可以使用M_PI常数来获取近似值。这个常数在大多数系统上都定义为一个double类型。

如果需要更精确的pi值,我们可以使用多精度计算库,如Boost库GMP库

以下是使用cmath库和Boost库计算pi的示例代码:

使用cmath库
#include <iostream>
#include <cmath>
 
int main()
{
    std::cout << std::fixed << std::setprecision(17) << M_PI << '\n';
    return 0;
}

输出:

3.14159265358979312

在本例中,std::fixedstd::setprecision(n)函数用于将输出浮点数的精度设置为n位小数。

使用Boost库
#include <iostream>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/math/constants/constants.hpp>

int main()
{
    using namespace boost::multiprecision;
    using std::cout;
    using std::endl;

    cpp_dec_float_100 pi = boost::math::constants::pi<cpp_dec_float_100>();
    cout << std::fixed << std::setprecision(100) << pi << endl;
    return 0;
}

输出:

3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019

在本例中,我们使用了Boost库中的一个高精度浮点类型cpp_dec_float_100boost::math::constants::pi函数返回一个指定精确度的pi值。在此例中,我们将精确度设置为100位小数。