Chapter 3. Using Mathematical Operators
3.0. Introduction
Almost every sketch uses mathematical operators to manipulate the value of variables. This chapter provides a brief overview of the most common mathematical operators. As the preceding chapter is, this summary is primarily for nonprogrammers or programmers who are not familiar with C or C++. For more details, 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.
Note
Make sure your result will not exceed the maximum size of the destination variable. See Recipe 2.2.
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 and division have a higher precedence than addition and subtraction, so ...
Get Arduino Cookbook 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.