C++ Math
Lesson outline
Introduction to C++ Math
C++ provides a wide range of mathematical operations using both built-in operators and the
The
Basic Arithmetic Operators
| Operator | Operation | Example | Result |
|---|---|---|---|
| + | Addition | 5 + 2 | 7 |
| - | Subtraction | 5 - 2 | 3 |
| * | Multiplication | 5 * 2 | 10 |
| / | Division | 5.0 / 2 | 2.5 |
| % | Modulus (remainder) | 5 % 2 | 1 |
| ++ | Increment | x++ (x starts 5) | x becomes 6 |
| -- | Decrement | x-- (x starts 5) | x becomes 4 |
Common Math Functions
The
| Function | Description | Example | Result |
|---|---|---|---|
| sqrt(x) | Square root | sqrt(25) | 5 |
| pow(x,y) | x raised to the power y | pow(2,3) | 8 |
| abs(x) | Absolute value | abs(-5) | 5 |
| ceil(x) | Round upward | ceil(3.2) | 4 |
| floor(x) | Round downward | floor(3.8) | 3 |
| round(x) | Round to nearest | round(3.5) | 4 |
| fmod(x,y) | Floating-point remainder | fmod(5.5,2) | 1.5 |
Trigonometric Functions
C++ includes standard trigonometric functions that use radians:
Exponential and Logarithmic Functions
For exponents and logarithms,
Random Number Generation
Modern C++ (C++11 and later) provides robust random number facilities in
Mathematical Constants
C++20 introduced standardized mathematical constants in
Practical Math Examples
Examples of math in everyday programs:
Best Practices
- Prefer double over float for greater precision
- Be aware of floating-point rounding errors
- Use parentheses to clarify complex expressions
- For advanced needs, consider libraries like Boost.Math
- Always initialize variables before using them in calculations