Math
classWe start today with a little segment I call Program This. I throw a problem at you and you spend a few moments solving it with your neighbor. Here goes:
You get a cryptic text saying, “Something big is going to happen in 1357 hours.” This kind of thing happens a lot, and you like to add a calendar entry on your phone for these targeted days reminding you to keep your eyes open. You decide to write a program to help turn the given number of hours into the time of this big something. How many full days away is it? At what time of the day will it occur?
Focus on the contents of your main
method. Use ideas we’ve talked about so far in the class.
Now that we’ve introduced the idea of variables and types, let’s practice evaluating some expressions operation by operation. The Practice-It! website is a great source for challenges. Here’s an expression from the expressions2 problem, solved one operation at a time:
4.0 / 2 * 9 / 2
2.0 * 9 / 2
18.0 / 2
9.0
Note how the types propagate through the intermediate results. Here’s another one:
double x = 17 % 10 / 4;
double x = 7 / 4;
double x = 1;
Note that even though we are storing the expression in a double
, the right-hand side gets evaluated first using integer division. We lose the fraction.
This seems like a good time to discuss the spectrum of numeric types: byte
, short
, int
, long
, float
, and double
. We’ll looking at changing between types, both implicitly and explicitly (through casting). We’ll also examine why so many different types exist by timing some mathematical operations.
Finally, we saw last time that we could give names to our data to make our expressions more meaningful. We’ll see today that we can give meaningful names to not only data, but entire operations. We may have a routine or process that we’d like to use again and again, liking finding the minimum of two numbers or determining the hypotenuse of a right triangle. Instead of having to write out the steps of these routines every time we need them, we’ll package them up in a big black box and invoke them succinctly through their reusable name. We’ll make use of some black boxes that are already available to us in the Math
class by solving these problems:
n
pictures, all the same size. How can you lay them out so that there are as many rows as there are columns?package lecture0911;
public class MathProblems {
public static void main(String[] args) {
double average = 5.27;
double nextWhole = Math.ceil(average);
System.out.println(nextWhole);
}
}
Comments