CPP Tutorial



C++ MATH


Mathematical Operations in C++

C++ supports basic arithmetic operations using operators, and provides a rich set of mathematical functions via the <cmath> library.


Basic Arithmetic Operators

  • + : Addition
  • - : Subtraction
  • * : Multiplication
  • / : Division (integer or floating-point)
  • % : Modulus (remainder of integer division)

Example:

#include <iostream>
using namespace std;

int main() {
    int a = 15, b = 4;

    cout << "a + b = " << (a + b) << endl;   // 19
    cout << "a - b = " << (a - b) << endl;   // 11
    cout << "a * b = " << (a * b) << endl;   // 60
    cout << "a / b = " << (a / b) << endl;   // 3 (integer division)
    cout << "a % b = " << (a % b) << endl;   // 3 (remainder)

    return 0;
}
  

Using <cmath> Library

For advanced math functions like power, square root, trigonometry, logarithms, etc., include the cmath header.

Common cmath Functions:

  • pow(base, exponent) - Calculate power
  • sqrt(x) - Square root
  • abs(x) - Absolute value
  • ceil(x) - Round up
  • floor(x) - Round down
  • sin(x), cos(x), tan(x) - Trigonometric functions (x in radians)
  • log(x) - Natural logarithm (base e)
  • log10(x) - Logarithm base 10

Example Using cmath:

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    double x = 9.0;
    double y = 2.0;

    cout << "Power: " << pow(x, y) << endl;        // 9^2 = 81
    cout << "Square Root: " << sqrt(x) << endl;   // √9 = 3
    cout << "Absolute: " << abs(-7.5) << endl;    // 7.5
    cout << "Ceil: " << ceil(4.3) << endl;        // 5
    cout << "Floor: " << floor(4.7) << endl;      // 4
    cout << "Sine of 90 degrees (in radians): " << sin(3.14159/2) << endl; // ~1

    return 0;
}
  

Notes:

  • Trigonometric functions use radians, not degrees. To convert degrees to radians, multiply degrees by π/180.
  • For integer absolute value, use abs(). For floating-point, use fabs() from cmath.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review