本文介绍了最佳平台独立pi常数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道您可以使用:

#define _USE_MATH_DEFINES

然后:

M_PI

以获得常数pi。但是,如果我没有记错(欢迎评论),则取决于编译器/平台。那么,使用pi常量从Linux移植到其他系统时不会引起任何问题的最可靠方法是什么?

to get the constant pi. However, if I remember correctly (comments welcome) this is compiler/platform dependent. So, what would be the most reliable way to use a pi constant that won't cause any problems when I port it from Linux to other systems?

我知道我可以只定义一个float / double,然后自己将其设置为一个四舍五入的pi值,但我真的很想知道是否存在指定的机制。

I know that I could just define a float/double and then set it to a rounded pi value myself, but I'd really like to know if there is a designated mechanism.

推荐答案

上有一篇有关生成pi的不同选项的文章:他们讨论了中的一些选项,不是平台无关的:

Meeting C++ has an article on the different options for generating pi: C++ & π they discuss some of the options, from cmath, which is not platform independent:

double pi = M_PI;
std::cout << pi << std::endl;

并来自:

std::cout << boost::math::constants::pi<double>() << std::endl

并使用,删除了 constexpr ,因为SchighSchagh指出这与平台无关:

and using atan, with constexpr removed since as SchighSchagh points out that is not platform independent:

 double const_pi() { return std::atan(1)*4; }

我将所有方法收集到:

#include <iostream>
#include <cmath>
#include <boost/math/constants/constants.hpp>

double piFunc() { return std::atan(1)*4; }

int main()
{
    double pi = M_PI;
    std::cout << pi << std::endl;
    std::cout << boost::math::constants::pi<double>() << std::endl ;
    std::cout << piFunc() << std::endl;
}



C ++ 2a pi_v



在C ++ 2a中,我们应该得到:

#include <numbers>
#include <iostream>

int main() {
     std::cout<< std::numbers::pi_v<double> <<"\n";
}

这篇关于最佳平台独立pi常数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 15:07
查看更多