|
home—info—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
We start by trying some expressions from lecture, to confirm that Java doesn't always give correct arithmetic answers. Predict the result of each expression to your partner, then try them out:
long n = 2000000000; n + n |
Challenge: For each of above, classify the error as
Challenge question:
Remember that /, if given two integers, returns the quotient. The remainder can be obtained by % (pronounced “mod” or “modulo” in addition to “remainder”). Predict the result of each expression to your partner, then try them out:
int m = 260; int n = 100; m/n (double) m // Casting. double m // Error. (double) m / (double) n // integer division, or floating-point division? ((double) m) / ((double) n) // Casting (w/ additional parens, for clarity?) |
Task: Delicious SugarBomb donuts cost 65 cents each. A robot wants to be cashier, and needs to know what to say to customers, after the customer has told it how many donuts are desired. Complete the following function to help the robot out.
/** * @param ____ The number of donuts ordered. * @return A String telling the customer how many * dollars and cents their order comes to. * donutOrder(4) = "4 donuts cost 2 dollars and 60 cents." * donutOrder(__) = ______________________________________ * donutOrder(__) = ______________________________________ */ String donutOrder( ___ ____ ) { } |
Include comments and test cases, of course. Use a NAMED_CONSTANT to represent the price of a single donut.
If you finish the preceding problem,
Edict of Programming: Do not use == with doubles.After all, what is the value of this expression?
(2.0 - 1.1) == 0.9 |
Task, part 1: Write a function nearlyEqual which takes in two doubles, and returns whether or not they are within 0.001 of each other. (Use a named-constant for the tolerance.)
Task, part 2: Actually, we should look at an relative difference between two terms, rather than an absolute difference. After all, 4.000000e6 dollars is practically equal to 4.000001e6 dollars, even though the difference between these two is one (which is far exceeds our tolerance).
Modify your program so that it returns true if
the ratio of the two numbers is close to 1:
that is, if
We won't finish this last problem in lab today, but it is worth completing as quiz1-study-material.
1 A more subtle wrinkle: is your function symmetric — that is, if your program says that a is nearly equal to b, does that mean it will always say that b is nearly equal to a? If not, is this easy to fix? Is is important to fix it? ↩
home—info—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
©2007, Ian Barland, Radford University Last modified 2007.Aug.25 (Sat) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |