我想在一些C++程序中使用PI常数和三角函数。我用include <math.h>得到三角函数。但是,在这个头文件中似乎没有PI的定义。
在不手动定义PI的情况下,如何获得PI?
发布于 2009-11-13 08:28:16
在一些(特别是旧的)平台上(请参阅下面的注释),您可能需要
#define _USE_MATH_DEFINES然后包括必要的头文件:
#include <math.h>而pi的值可以通过以下方式访问:
M_PI在我的math.h (2014年)中,它被定义为:
# define M_PI 3.14159265358979323846 /* pi */但请查看您的math.h以获得更多信息。“旧”math.h的摘录(2009年):
/* Define _USE_MATH_DEFINES before including math.h to expose these macro
* definitions for common math constants. These are placed under an #ifdef
* since these commonly-defined names are not part of the C/C++ standards.
*/然而:
_USE_MATH_DEFINESlong double值作为M_PIl扩展提供:定义M_PIl 3.1415926535793238462643383279502884 L /* pi */发布于 2009-11-13 08:26:27
Pi可计算为atan(1)*4。您可以以这种方式计算值并缓存它。
发布于 2019-07-31 07:26:55
std::numbers::pi C++20
终于,它到达了: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编译和运行:
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.141592653589793238462643383279502884197169399375105820974944Ubuntu20.04 amd64,GCC 10.2.0测试
已接受的提案说明:
5.0.表tab:cpp.library.headers中的“header”标头,需要添加一个新的
<math>头。 ..。 命名空间std {命名空间数学{模板内联常数T pi_v =未指定;
当然还有一个std::numbers::e :-) 如何计算欧拉常数或欧拉驱动的C++?
这些常量使用C++14变量模板特性:C++14变量模板:它们的目的是什么?有什么用法吗?
在草案的早期版本中,常量位于std::math::pi:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p0631r7.pdf下面。
https://stackoverflow.com/questions/1727881
复制相似问题