Expand All

Numbers And Arithmetic

Goals

  • Understand the difference between an integer and a float

  • Perform basic arithmetic operations

Step 1

In programming, we like to distinguish between different kinds of numbers. Here, we'll talk about integers (whole numbers) and floats (decimals).

Type this in irb:
1.class
1.0.class

You'll notice that 1.class and 1.0.class are actually 2 different kinds of objects.

With that in mind, let's see how that plays into performing arithmetic operations.

Step 2

Type this in irb:
1 + 2
1.0 + 2.0
1 + 2.0

Here, you'll notice that performing an operation on 2 integers will produce an integer and operating on 2 floats will produce a float, but mixing an integer with a float would actually produce a float.

Step 3

Type this in irb:
2 - 1
2.0 - 1.0
2.0 - 1

Just like addition, we can perform subtraction on integers and floats interchangeably.

Step 4

Type this in irb:
2 * 3
2.0 * 3
2.0 * 3.0

Likewise, we can perform multiplication on floats and integers.

Step 5

Type this in irb:
4 / 2
8 / 2
6 / 4
6 / 4.0

Division can be performed similarly. Notice the difference in the results of the last two lines. When dividing two integers, ruby will perform mathematical truncation, where the expected result 1.5 becomes 1

Step 6

Type this in irb:
4 / 0

Uh oh! Notice how we did not get a result here. The ruby interpreter raised an error. These errors tell the programmer that they tried to do something that the interpreter does not like or cannot use. Each error has a classification and a message. In this case, we get a ZeroDivisionError with the message: divided by 0

Reto(s)

Write a calculator that performs addition. Your program should prompt the user to enter two numbers and output the sum.

Here is a sample of how the program might run. The > has been used below to indicate that the user should input the value proceeding it.

What is the first number?
> 2
What is the second number?
> 4
The sum is 6

Next Step: