C++ Math

➗ C++ Math

C++ mein Math operations do tarah se hote hain:
1️⃣ Basic arithmetic operators
2️⃣ Math library functions (<cmath>)


🔹 1. Basic Math Operators

int a = 10, b = 3;

cout << a + b; // Addition → 13
cout << a - b; // Subtraction → 7
cout << a * b; // Multiplication → 30
cout << a / b; // Division → 3 (integer division)
cout << a % b; // Modulus → 1

Floating Division

cout << 10.0 / 3; // 3.33333

🔹 2. Math Functions (<cmath>)

#include <cmath>

Common Math Functions

Function Work Example
sqrt(x) Square root sqrt(16) → 4
pow(x,y) Power pow(2,3) → 8
abs(x) Absolute value abs(-5) → 5
round(x) Nearest integer round(4.6) → 5
ceil(x) Round up ceil(4.2) → 5
floor(x) Round down floor(4.9) → 4
log(x) Natural log log(2.7)
sin(x) Sine (radians) sin(0)
cos(x) Cosine cos(0)
tan(x) Tangent tan(0)

🔹 3. Examples

Square Root & Power

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

int main() {
cout << sqrt(25) << "\n"; // 5
cout << pow(3, 2) << "\n"; // 9
return 0;
}


Rounding Functions

double x = 4.7;

cout << round(x); // 5
cout << ceil(x); // 5
cout << floor(x); // 4


Absolute Value

int x = -20;
cout << abs(x); // 20

🔹 4. Trigonometry (Radians)

double angle = 0;
cout << sin(angle); // 0
cout << cos(angle); // 1

⚠️ Trigonometric functions radians mein kaam karti hain, degrees mein nahi.


🔹 5. Min & Max

cout << max(10, 20); // 20
cout << min(10, 20); // 10

❌ Common Mistakes

cout << sqrt(-4); // ❌ invalid (NaN)
pow(2, 3); // ❌ without <cmath>

✔ Correct:

#include <cmath>

📌 Summary

  • Basic math → + - * / %

  • Advanced math → <cmath> functions

  • pow, sqrt, round, ceil, floor very common

  • Trigonometry uses radians

You may also like...