C++ supports basic arithmetic operations using operators, and provides a rich set of mathematical functions via the <cmath> library.
+ : Addition- : Subtraction* : Multiplication/ : Division (integer or floating-point)% : Modulus (remainder of integer division)
#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;
}
<cmath> Library
For advanced math functions like power, square root, trigonometry, logarithms, etc., include the cmath header.
cmath Functions:pow(base, exponent) - Calculate powersqrt(x) - Square rootabs(x) - Absolute valueceil(x) - Round upfloor(x) - Round downsin(x), cos(x), tan(x) - Trigonometric functions (x in radians)log(x) - Natural logarithm (base e)log10(x) - Logarithm base 10cmath:
#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;
}
π/180.abs(). For floating-point, use fabs() from cmath.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!