Here are the normal math operators that work on integers and floating point numbers:
-(subtract; or a negative number, e.g.
int x = -5)
Here are somewhat-unique math operators that work with integers:
13 / 5is 2 because 5 goes into 13 two times)
13 % 5is 3 because the remainder of 5/13 is 2)
/ works as you would expect with floating point numbers
1.2 / 5.6 is about 0.214).
Precedence works the same as you would expect:
* / %
+ - so
(5 + 6 % 4 - (3 + 4) /
2) equals 4 as you would expect. You can use parentheses to
clarify the math.
You can use the following shorthand for changing the values of variables. The shorthand form is shown, then the equivalent form is described in comments.
What’s the difference between
assignment expression actually has a value. So
x = 5 turns into the
value 5 (and changes
x to equal 5). That makes the following
y = x = 5, which sets
y equal to the value
x = 5,
which is the value 5.
The difference is that
x++ gives back the old value of
x (but also
x then gives its value. So
x is 5, and we have
y = x++ then
y is 5 and
x is 6. On the
other hand, if we have
y = ++x then
y is 6 and
x is 6.
Variables of type
bool have the following special operators:
This example shows use of several mathematical functions and operators.
Here is the example again, but this time with a variable
In these examples, various useful math functions were used. Here is a larger list. These all come from
cmath (which must be “included”).
pow(a, b)– raise
ato the power
bshould have type
exp(a)– raise Euler’s number e to the power
log(a)– find the natural logarithm of
log10(a)– find the “base 10” logarithm of
sqrt(a)– find the square root of
sin(a)– the result of sine(a) (
double, in radians)
asin(a)– the arc cosine/sine of
a; answer is in radians (
double, as is the answer)
This code converts teaspoons to other units of measurement.