# PI Constant in C++

In this tutorial, we will learn **how to use the PI constant in C++**.

PI is a mathematical constant which we use in various mathematical calculations ranging from simple finding area of a circle to more complex Stoke’s theorem in mathematics. C++ has a predefined constant in its math library which we can use to access the value of pi wherever needed in our program.

We use the following header file :

#define _USE_MATH_DEFINES #include <cmath>

Here, _USE_MATH_DEFINES is a #define macro. Later in the program, we use M_PI to access the value of PI. In C++, the value of M_PI is 3.14159265358979323846.

Below I write a simple program to print the value of PI.

## Print the value of PI in C++

#define _USE_MATH_DEFINES #include<cmath> #include<iostream> using namespace std; int main() { cout << "value of pi is = " << M_PI << endl; return 0; }

Output:

value of pi is = 3.14159

Now that we know how to use the constant, let’s find out the volume of a sphere with radius r. In this program, we use the formula for the volume of a sphere which is 4/3 π r^3.

### Program to find the volume of a sphere in C++

#define _USE_MATH_DEFINES #include<cmath> #include<iostream> using namespace std; int main() { int r; float v; cout << "Enter the value of radius : "; cin >> r; v = float(4) / float(3) * M_PI * r * r * r; cout << "volume of the sphere is : " << v << endl; return 0; }

Output :

Enter the value of radius : 4 volume of the sphere is : 268.083

You can also always define your own value of pi and use it in a program.

## Set Value of PI constant in C++

#include<iostream> using namespace std; const double PI = 3.141592653589793238463; //value of pi int main() { cout << "value of pi is : " << PI; }

Output :

value of pi is = 3.14159

Hope this was helpful. Enjoy Coding!

Also read :

## Leave a Reply