Simple Arithmetic

Learn to Program, Third Edition — by Chris Pine (13 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Integers and Floats | TOC | Progress Checkpoint 👉

We can write programs to solve arithmetic problems like a calculator would. For addition and subtraction, we use + and -, as we saw. For multiplication, we use *, and for division we use /.

Let’s expand the calc.rb program a little. Try coding this program:

​1: puts 1.0 + 2.0 
​2: puts 2.0 * 3.0
​3: puts 5.0 - 8.0
​4: puts 9.0 / 2.0

This is what the program returns:

​<= 3.0
​ 6.0
​ -3.0
​ 4.5

(The spaces in the program aren’t important; they simply make the code easier to read.) Well, that result wasn’t too surprising. Now let’s try it with integers:

​1: puts 1+2
​2: puts 2*3
​3: puts 5-8
​4: puts 9/2

This is mostly the same, right?

​<= 3
​ 6
​ -3
​ 4

Um…except for that last one. When you do arithmetic with integers, you’ll get integer answers. When Ruby can’t get the “correct” answer, it always rounds down. (Of course, 4 is the correct answer in integer arithmetic for 9/2. But it might not be the answer you were expecting.)

Perhaps you’re wondering why you’d use integer division. What’s it good for?

Well, let’s say you’re going to the movies but you have only $9. Back in Ye Olde Portland, Oregon, you could see a movie at the…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.