Mathematical Operations
3.0 Introduction
Almost every sketch uses mathematical operations to manipulate the value of variables. This chapter provides a brief overview of the most common mathematical operations. If you are already familiar with C or C++, you may be tempted to skip this chapter, but we suggest you review it because there are some idioms used by Arduino programmers that you may encounter even if you don’t use them yourself (such as the use of bitSet
to change the value of a bit). If you are new to C and C++, see one of the C reference books mentioned in the Preface.
3.1 Adding, Subtracting, Multiplying, and Dividing
Problem
You want to perform simple math on values in your sketch. You want to control the order in which the operations are performed and you may need to handle different variable types.
Solution
Use the following code:
int
myValue
;
myValue
=
1
+
2
;
// addition
myValue
=
3
-
2
;
// subtraction
myValue
=
3
*
2
;
// multiplication
myValue
=
3
/
2
;
// division (the result is 1)
Discussion
Addition, subtraction, and multiplication for integers work much as you expect.
Integer division truncates the fractional remainder in the division example shown in this recipe’s Solution; myValue
will equal 1 after the division (see Recipe 2.3 if your application requires fractional results):
int
value
=
1
+
2
*
3
+
4
;
Compound statements, such as the preceding statement, may appear ambiguous, but the precedence (order) of every operator is well defined. Multiplication ...
Get Arduino Cookbook, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.