In the previous article, the arithmetic types and their literals were discussed. There are C++ language features and C++ standardl ibrary components that allow you to perform computation with integers and real numbers. You should already be familiar with expression. An expression is a sequence of operators and operands which may specify a computation and result in a value. Some operators you should be familiar with include: simple assignment, addition, subtraction, multiplication, and division.
In addition to simple assignment, the follownig other assignment operators are provided:
| Operator | Syntax | Equivalent expression |
|---|---|---|
| Addition assignment | a += b | a = a + b |
| Subtraction assignment | a -= b | a = a - b |
| Multiplication assignment | a *= b | a = a * b |
| Division assignment | a /= b | a = a / b |
| Modulo assignment | a %= b | a = a % b |
| Operator | Syntax | Meaning |
|---|---|---|
| Pre-increment | ++a | Increment a and return the new value |
| Post-increment | a++ | Increment a and return the old value |
| Pre-decrement | --a | Decrement a and return the new value |
| Post-decrement | a-- | Decrement a and return the old value |
The expression ++a is exactly equivalent to a += 1. The expression --a is exactly equivalent to a -= 1.
By including the <cmath> header file, you gain access to the common mathematical functions of the C++ numerics library.
Here are some expressions using the common mathematical functions:
| Expression | Meaning |
|---|---|
| abs(x) | Absolute value of integer value x |
| fabs(x) | Absolute value of floating-point value x |
| exp(x) | e raised to the power of x |
| log(x) | Natural logarithm of x |
| log10(x) | Base 10 logarithm of x |
| sqrt(x) | Square root of x |
| sin(x) | Sine of x |
| cos(x) | Cosine of x |
| tan(x) | Tangent of x |
| asin(x) | Arc sine of x |
| acos(x) | Arc cosine of x |
| atan(x) | Arc tangent of x |
| ceil(x) | Rounds up x to the nearest integer |
| floor(x) | Rounds down x to the nearest integer |
| pow(x, y) | x raised to the power of y |
All trigonometric functions expect an argument in radians.
For the full reference of these functions visit: http://en.cppreference.com/w/cpp/numeric/math
In a later article, the specific implicit conversions that take place when mixing integer values with floating-point values inside expressions will be discussed.
As a general rule though, the result of a non-assignment expression using different arithmetic types is a value that has the same type as the operand having the largest object representation in memory, with floating-point types having priority.
Thus, if you add a double to an int, the result is double. If you subtract a short int from a long int, the result is a long int. If you divide a float by a long double, the result is a long double. If you multiply a float with an int, the result is a float.