C - C++ Mathematical Constants

The cmath library actually provides many mathematical constants that you can make use of.

To include the mathematical constants, you need to use a #define macro called _USE_MATH_DEFINES and add it before importing the cmath library:

#define _USE_MATH_DEFINES
 
#include <cmath>
#include <iostream>
 
int main() { 
  std::cout << M_PI << " " << M_E << " " << M_SQRT2 << endl;
  return 0;
}

There are quite a few constants on offer.

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
eM_E2.71828182845904523536
log_2(e)M_LOG2E1.44269504088896340736
log_10(e)M_LOG10E0.434294481903251827651
log_e(2)M_LN20.693147180559945309417
log_e(10)M_LN102.30258509299404568402

NOTE: It is not best practice within C++ to use #defines for mathematical constants!

  • Instead, as an example, you should use const double pi = 3.14159265358979323846;.
  • The #defines are a legacy feature of C.