Figure 3-7
shows what you should see in the Serial Monitor after this code runs.
To take a slightly more complex example, the formula for converting a temperature in
degrees Centigrade into degrees Fahrenheit is to multiply it by 5, divide by 9, and then add
32. So you could write that in a sketch like this:
Figure 3-7
Simple arithmetic
There are a few things to notice here. First, note the following line:
When we write such a line, we are actually doing two things:
We are declaring an
int
variable called
degC
, and we are saying that its initial value will be 20. Alternatively, you
could separate these two things and write the following:
You must declare any variable just once, essentially telling
the compiler what type of
variable it is—in this case,
int
. However, you can assign
the variable a value as many
times as you want:
So, in the Centigrade to Fahrenheit example, you
are defining the variable
degC
and
giving it an initial value of 20, but when you define
degF
, it does not get an initial value.
Its value gets assigned on the next line, according to the conversion formula, before being
sent to the Serial Monitor for you to see.
Looking at the expression, you can see that you use the asterisk (
*
) for multiplication
and the slash (
/
) for division.
The arithmetic operators
+, −, *
, and
/
have an order of
precedence—that is, multiplications are done first,
then divisions, then additions and
subtractions. This is in accordance with the usual use of arithmetic. However, sometimes it
makes it clearer to use parentheses in the expressions. So, for example,
you could write
the following:
The expressions that you write can be as long and complex as you need them to be, and
in addition to the usual arithmetic operators, there are other less commonly used operators
and a big collection of various mathematical functions that are available to you. You will
learn about these later.
Dostları ilə paylaş: