Mathematical Constants in C++
In this tutorial, we will learn how to use the mathematical constants in C++.
We use mathematical constants in various places from simple mathematical calculations to physics to chemistry and even financial problems. C++ has a few predefined constants in its math library which we can use to access the values 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. C++ has the following constants with their values :
Symbol | Expression | Value |
---|---|---|
M_E | e | 2.71828182845904523536 |
M_LOG2E | log2(e) | 1.44269504088896340736 |
M_LOG10E | log10(e) | 0.434294481903251827651 |
M_LN2 | ln(2) | 0.693147180559945309417 |
M_LN10 | ln(10) | 2.30258509299404568402 |
M_PI | pi | 3.14159265358979323846 |
M_PI_2 | pi/2 | 1.57079632679489661923 |
M_PI_4 | pi/4 | 0.785398163397448309616 |
M_1_PI | 1/pi | 0.318309886183790671538 |
M_2_PI | 2/pi | 0.636619772367581343076 |
M_2_SQRTPI | 2/sqrt(pi) | 1.12837916709551257390 |
M_SQRT2 | sqrt(2) | 1.41421356237309504880 |
M_SQRT1_2 | 1/sqrt(2) | 0.707106781186547524401 |
Here I have written a simple program to access the values :
Program to show Mathematical Constants in C++ :
#define _USE_MATH_DEFINES #include<cmath> #include<iostream> using namespace std; int main() { cout << "log10(e) = " << M_LOG10E<< endl << "exp = " << M_E << endl << "sqrt(2) = " << M_SQRT2 << endl; return 0; }
Output :
log10(e) = 0.434294 exp = 2.71828 sqrt(2) = 1.41421
Now, we write another program to find the area of a circle using M_PI constant.
Program to find the area using M_PI :
#define _USE_MATH_DEFINES #include<cmath> #include<iostream> using namespace std; int main() { int r; float a; cout << "Enter the value of radius : "; cin >> r; a = M_PI * r * r ; cout << "area of the circle is : " << a << endl; return 0; }
Output :
Enter the value of radius : 9 area of the circle is : 254.469
Hope this was helpful. Enjoy Coding!
Also read :
Leave a Reply