Does C++11, 14, 17 or 20 introduce a standard constant for pi?

前端 未结 6 1229
失恋的感觉
失恋的感觉 2020-12-08 08:56

There is a rather silly problem with the number pi in C and C++. As far as I know M_PI defined in math.h is not required by any standard.

N

6条回答
  •  心在旅途
    2020-12-08 09:29

    As others said there is no std::pi but if you want precise PI value you can use:

    constexpr double pi = std::acos(-1);
    

    This assumes that your C++ implementation produces a correctly-rounded value of PI from acos(-1.0), which is common but not guaranteed.

    It's not constexpr, but in practice optimizing compilers like gcc and clang evaluate it at compile time. Declaring it const is important for the optimizer to do a good job, though.

提交回复
热议问题