> For the complete documentation index, see [llms.txt](https://alham-rizvi.gitbook.io/alhamrizvi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://alham-rizvi.gitbook.io/alhamrizvi/c++-notes/09.-useful-math-functions.md).

# 09. Useful Math Functions

C++ ships with a bunch of ready-made **math** functions so you don't have to write them yourself. Most live in the `<cmath>` header; `std::max`/`std::min` live in `<algorithm>`.

```cpp
#include <iostream>
#include <cmath>
#include <algorithm>
```

***

### `std::max` and `std::min`

Returns the bigger (or smaller) of two values.

```cpp
#include <iostream>
#include <algorithm>

int main() {
    int a = 10;
    int b = 25;

    std::cout << "Max: " << std::max(a, b) << '\n'; // 25
    std::cout << "Min: " << std::min(a, b) << '\n'; // 10

    return 0;
}
```

Works with any comparable type — including `double`:

```cpp
double price1 = 19.99;
double price2 = 24.50;
std::cout << std::min(price1, price2) << '\n'; // 19.99
```

***

### `pow` — raise to a power

`pow(base, exponent)` — computes `base ^ exponent`.

```cpp
#include <iostream>
#include <cmath>

int main() {
    double result = pow(2, 3); // 2^3

    std::cout << result << '\n'; // 8

    return 0;
}
```

> `pow` always returns a `double`, even for whole-number results — cast to `int` if you need a clean integer.

```cpp
int squared = static_cast<int>(pow(5, 2)); // 25
```

***

### `sqrt` — square root

```cpp
#include <iostream>
#include <cmath>

int main() {
    double result = sqrt(64);

    std::cout << result << '\n'; // 8

    return 0;
}
```

***

### `abs` — absolute value

Strips the sign, always returns a positive (or zero) value.

```cpp
#include <iostream>
#include <cmath>

int main() {
    int a = -15;
    double b = -3.7;

    std::cout << abs(a) << '\n';  // 15
    std::cout << abs(b) << '\n';  // 3.7

    return 0;
}
```

> Tip: `abs` for integers technically comes from `<cstdlib>`, and `<cmath>`'s version handles floating-point — but in practice `#include <cmath>` covers you for both in most compilers.

***

### `round`, `ceil`, and `floor`

All three deal with turning a decimal into a whole number, but they behave differently:

| Function  | Behavior                           | `4.3` → | `4.7` → | `-4.3` → |
| --------- | ---------------------------------- | ------- | ------- | -------- |
| `round()` | Rounds to the nearest whole number | `4`     | `5`     | `-4`     |
| `ceil()`  | Always rounds **up**               | `5`     | `5`     | `-4`     |
| `floor()` | Always rounds **down**             | `4`     | `4`     | `-5`     |

```cpp
#include <iostream>
#include <cmath>

int main() {
    double value = 4.3;

    std::cout << "round: " << round(value) << '\n'; // 4
    std::cout << "ceil:  " << ceil(value)  << '\n'; // 5
    std::cout << "floor: " << floor(value) << '\n'; // 4

    return 0;
}
```

> These also return `double` — cast to `int` if you need a whole-number type.

***

### More cool examples

#### 1. Distance between two points (uses `sqrt` and `pow`)

```cpp
#include <iostream>
#include <cmath>

int main() {
    double x1 = 0, y1 = 0;
    double x2 = 3, y2 = 4;

    double distance = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));

    std::cout << "Distance: " << distance << '\n'; // 5

    return 0;
}
```

#### 2. Clamping a value between a min and max

```cpp
#include <iostream>
#include <algorithm>

int main() {
    int health = 120;

    int clamped = std::min(100, std::max(0, health)); // keep between 0 and 100

    std::cout << "Clamped health: " << clamped << '\n'; // 100

    return 0;
}
```

#### 3. Rounding a price to the nearest whole dollar

```cpp
#include <iostream>
#include <cmath>

int main() {
    double price = 19.49;

    int roundedPrice = static_cast<int>(round(price));

    std::cout << "Rounded price: $" << roundedPrice << '\n'; // $19

    return 0;
}
```

#### 4. Figuring out how many boxes you need (`ceil` is perfect for this)

```cpp
#include <iostream>
#include <cmath>

int main() {
    int items = 47;
    int itemsPerBox = 10;

    int boxesNeeded = static_cast<int>(ceil(static_cast<double>(items) / itemsPerBox));

    std::cout << "Boxes needed: " << boxesNeeded << '\n'; // 5

    return 0;
}
```

#### 5. Absolute difference between two temperatures

```cpp
#include <iostream>
#include <cmath>

int main() {
    double temp1 = -5.5;
    double temp2 = 12.3;

    double difference = abs(temp1 - temp2);

    std::cout << "Difference: " << difference << '\n'; // 17.8

    return 0;
}
```

***

### Quick Recap

* `std::max(a, b)` / `std::min(a, b)` — from `<algorithm>`, pick the bigger/smaller value.
* `pow(base, exp)` — raise to a power.
* `sqrt(x)` — square root.
* `abs(x)` — absolute value (strip the sign).
* `round(x)` — nearest whole number.
* `ceil(x)` — always rounds up.
* `floor(x)` — always rounds down.
* Most of these live in `<cmath>` and return `double` — cast to `int` when you need a whole number.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://alham-rizvi.gitbook.io/alhamrizvi/c++-notes/09.-useful-math-functions.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
