Simple Arithmetic

So far, we have all the makings of a simple calculator. (Calculators always use floats, so if you want your computer to act just like a calculator, you should also use floats.) You type numbers using the digit keys (either at the top of your keyboard or on the numeric keypad). For decimal points, you use the period (or full-stop, normally close to the M key on the bottom row or over on the numeric keypad). Don’t, however, type commas into your numbers. If you enter 1,000,000, you’ll just confuse Ruby.

For addition and subtraction, we use + and -, as we saw. For multiplication, we use *, and for division we use /. Most keyboards have these keys in the numeric keypad on the far-right side, but you can also use Shift8 and / (the same key as the ? key). Let’s try to expand our calc.rb program a little. Try coding this program:

puts 1.0 + 2.0
puts 2.0 * 3.0
puts 5.0 - 8.0
puts 9.0 / 2.0

This is what the program returns:

3.0
6.0
-3.0
4.5

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

puts 1+2
puts 2*3
puts 5-8
puts 9/2

This is mostly the same, right?

3
6
-3
4

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

Perhaps you’re wondering what integer division is good for. Well, let’s say you’re going to the movies but you have only $9. When I lived in Portland a few years back, you could see a movie at the Bagdad for two bucks. (It was cheaper for two people to go to the Bagdad and get a pitcher of beer, good beer, than to go see a movie at your typical theater. And the seats all had tables in front of them! For your beer! It was heavenly!) Anyway, nostalgia aside, how many movies could you see at the Bagdad for nine bucks? 9/2...4 movies. You can see that 4.5 is definitely not the right answer in this case; they will not let you watch half of a movie or let half of you in to see a whole movie…some things just aren’t divisible.

So, now experiment with some programs of your own! If you want to write more complex expressions, you can use parentheses. For example:

puts 5 * (12-8) + -15
puts 98 + (59872 / (13*8)) * -51
5
-29227
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.170.92