Module 4: Real Numbers (no more fakes!)


Objectives

 

By the end of this module, for simple programs with real numbers, you will be able to:

 


Real-valued variables

 

Just like we did with integers, we can declare variables and assign values to them:

Another example:

Again, as with integers, the standard operators apply:

 

In-Class Exercise 1: Write a program to print out the area of a circle whose radius is 1.5 inches.
 

In-Class Exercise 2: Can you find a well-known formula or law in science or engineering that uses all four of the standard operators: +, -, *, /? If not, find one that uses as many as possible.
 

In-Class Exercise 3: Do the increment and decrement operators work with real numbers?
 

Now consider this simple example:

 

In-Class Exercise 4: Change the assignment to:

and see what prints. Explain the result.
 


Casting

 

Consider the following program:

 

In-Class Exercise 5: What you suppose will be printed? Try it. Then, change the program so that you initially assign the value of 1 to i and then assign i to x.
 

An assignment from an int to a double works fine:

 

About casting:

  • The assignment from int to double works because every int is a valid double value.

  • However, a double need not be a valid int.
           => Which is why the compiler complains.

  • However, we can force an assignment using an explicit cast (jargon alert!)

  • The result: the largest integer less than the real.
           => The result is 1 above.

  • An explicit cast is need even if the double's value happens to be an integer like 1.0.

  • As we'll see later, casting is a general operation that can be applied to different variable types.
 

In-Class Exercise 6: What do you get when you cast the real value 0.5 to an int?