# How to use PI in C++?

posted Aug 9

A PI is a mathematical expression that is used to derive the mathematical function of pi(π) in C++. We can use the value in various mathematical theorems in a pre-defined constant so it can be accessible in the program being developed.

Many C++ compilers do not have PI but define it in <cmath> header file M-PI as a non-standard extension. For example, you have to use an expression like #define_USE_MATH_DEFINES which ensures the PI appears.

## Example

Example of syntax to output the value of PI;

``````#define _USE_MATH_DEFINES

#include <cmath>

#include <iostream>

int main() {

std::cout << M_PI << " " << M_E << " " << M_SQRT2 << endl;

return 0;

}``````

### Output

`3.14159      2.71828      1.41421`

The output of the function will be the mathematical value of PI, which is 3.14159.  The cmath can also be used with acos function to return the mathematical value of the PI.  Herewhere we used C++ symbols for PI. you can find more about them in the table.

Mathematical ExpressionC++ symbolDecimal Representation
piM_PI3.14159265358979323846
pi/2M_PI_21.57079632679489661923
pi/4M_PI_40.785398163397448309616
1/piM_1_PI0.318309886183790671538
2/piM_2_PI0.636619772367581343076
2/sqrt(pi)M_2_SQRTPI1.12837916709551257390
sqrt(2)M_SQRT21.41421356237309504880
1/sqrt(2)M_SQRT1_20.707106781186547524401

The cmath library in C++ is used mostly in quantitative finance programs. The constant of the PI must be set and defined as a part of the feature of C++ programming's language.

Note: If you don't want to use the #define term above the int main() function then you can try this method. For example, const double pi = 3.14159265358979323846;

Hope this helps.

100 points
7 2