Introduction
Mathematics plays a crucial role in programming, helping to solve real-world problems efficiently. C++ provides a rich set of built-in mathematical functions to perform calculations. These functions are available in the<cmath> library and allow us to perform operations like exponentiation, logarithms, trigonometry, rounding, and more.
Including the <cmath> Library
Most mathematical functions in C++ are available in the <cmath> library. To use them, you need to include this header file at the beginning of your program:
1️⃣ Power and Square Root Functions
pow(base, exponent): Raises a number to a power.
sqrt(x): Computes the square root of a number.
2️⃣ Logarithmic and Exponential Functions
log(x): Returns the natural logarithm (base e).
log10(x): Returns the base-10 logarithm.
exp(x): Computes e^x (exponential function).
3️⃣ Trigonometric Functions
C++ provides trigonometric functions such assin(), cos(), and tan() that work with radians.
4️⃣ Rounding and Absolute Functions
ceil(x): Rounds up to the nearest integer.
floor(x): Rounds down to the nearest integer.
round(x): Rounds to the nearest integer.
abs(x): Returns the absolute value.
5️⃣ Fmod and Remainder Functions
fmod(x, y): Returns the remainder of x/y.
Common Errors and Solutions
| Error | Cause | Solution |
|---|---|---|
| Undefined function | <cmath> not included | Add #include <cmath> |
| Wrong trigonometric result | Angle in degrees instead of radians | Convert degrees to radians using M_PI / 180.0 |
| Incorrect logarithm | Using log(x) instead of log10(x) | Use log10(x) for base-10 logs |
Conclusion
Mathematical functions in C++ help solve complex problems in various domains. We explored:- Power and Square Root (
pow(),sqrt()) - Logarithms (
log(),log10()) - Trigonometry (
sin(),cos(),tan()) - Rounding (
ceil(),floor(),round()) - Absolute and Modulus (
abs(),fmod())