我想在一些c++程序中使用PI常数和三角函数。我得到三角函数包含<math。h>。然而,在这个头文件中似乎没有PI的定义。

如何获得PI而不手动定义它?


当前回答

C + + 20 std::数字pi

最后,它来了:http://eel.is/c++draft/numbers

main.cpp

#include <numbers> // std::numbers
#include <iomanip>
#include <iostream>

int main() {
    std::cout << std::fixed << std::setprecision(20);
    std::cout << "float       " << std::numbers::pi_v<float> << std::endl;
    std::cout << "double      " << std::numbers::pi << std::endl;
    std::cout << "long double " << std::numbers::pi_v<long double> << std::endl;
    std::cout << "exact       " << "3.141592653589793238462643383279502884197169399375105820974944" << std::endl;
}

其中,精确的计算结果为:

echo "scale=60; 4*a(1)" | BC_LINE_LENGTH=0 bc -l

如何使用Bash命令计算pi

编译并运行:

g++-10 -ggdb3 -O0 -std=c++20 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out

输出:

float       3.14159274101257324219
double      3.14159265358979311600
long double 3.14159265358979323851
exact       3.141592653589793238462643383279502884197169399375105820974944

在Ubuntu 20.04 amd64, GCC 10.2.0上测试

已接受的建议如下:

5.0. “头”(头) 在表[tab: cppp .library.]Headers],需要添加一个新的<math>头。 […] 命名空间STD { 命名空间math { template<typename T > inline constexpr T pi_v = undefined; Inline constexpr double PI = pi_v<double>;

还有一个std::numbers::e当然:-)如何计算欧拉常数或欧拉驱动在c++ ?

这些常量使用c++ 14变量模板特性:有什么使用例子吗?

在草案的早期版本中,常量位于std::math::pi: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p0631r7.pdf之下

其他回答

因为官方标准库没有定义常数PI,你必须自己定义它。因此,对于你的问题“如何获得PI而不手动定义它?”的答案是“你没有——或者你依赖于一些特定于编译器的扩展。”如果你不关心可移植性,你可以查看编译器手册。

c++允许你编写

const double PI = std::atan(1.0)*4;

但是这个常数的初始化不能保证是静态的。然而,g++编译器将这些数学函数作为内在函数处理,并能够在编译时计算这个常量表达式。

在c++ 20标准库中,π被定义为std::numbers::pi_v,用于浮点数、双精度数和长双精度数。

#include <numbers>
auto n = std::numbers::pi_v<float>;

并且可以专门化为用户定义的类型。

标准c++没有圆周率的常数。

许多c++编译器在cmath中定义M_PI(或在math.h中定义C)作为一个非标准扩展。在看到它之前,您可能必须#define _use_math_definitions。

c++ 14允许你执行静态constexpr auto pi = acos(-1);

来自math.h的Posix手册页:

   The  <math.h>  header  shall  provide for the following constants.  The
   values are of type double and are accurate within the precision of  the
   double type.

   M_PI   Value of pi

   M_PI_2 Value of pi/2

   M_PI_4 Value of pi/4

   M_1_PI Value of 1/pi

   M_2_PI Value of 2/pi

   M_2_SQRTPI
          Value of 2/ sqrt pi