C++ Math

C++ Math

C++ has a rich set of mathematical functions that allow you to perform math tasks on numbers.

Basic Math Operations

You can easily find the highest or lowest value of two numbers using max() and min():

Example

#include <iostream>
#include <cmath> // Include the cmath library
using namespace std;

int main() { cout << max(5, 10) << "\n"; // Outputs 10 cout << min(5, 10); // Outputs 5 return 0; }

The <cmath> Library

To use advanced math functions, you must include the <cmath> header file.

Example

#include <cmath>

cout << sqrt(64); // Outputs 8 (Square Root) cout << round(2.6); // Outputs 3 (Rounds to nearest integer) cout << log(2); // Outputs 0.693147 (Natural logarithm)

Other useful functions in the <cmath> library include abs() (absolute value), ceil(), floor(), and pow(). These are invaluable when writing complex algorithms or game physics!


Exercise

?

Which header file must be included to use advanced math functions like sqrt()?