Java Reference
In-Depth Information
stored in n. Remedy: Use Math.round to convert floating-point numbers to
integers. The round method returns the closest integer.
int n = (int) Math.round(100 * f); // OK, n is 435
H OW T O 4.1: Carrying Out Computations
Many programming problems require that you use mathematical formulas to
compute values. It is not always obvious how to turn a problem statement into a
sequence of mathematical formulas and, ultimately, statements in the Java
programming language.
Step 1 Understand the problem: What are the inputs? What are the desired outputs?
For example, suppose you are asked to simulate a postage stamp vending machine.
A customer inserts money into the vending machine. Then the customer pushes a
ȒFirst class stampsȓ button. The vending machine gives out as many first-class
stamps as the customer paid for. (A first-class stamp cost 39 cents at the time this
topic was written.) Finally, the customer pushes a ȒPenny stampsȓ button. The
machine gives the change in penny (1-cent) stamps.
In this problem, there is one input:
ȗ The amount of money the customer inserts
There are two desired outputs:
ȗ The number of first-class stamps the machine returns
ȗ The number of penny stamps the machine returns
Step 2 Work out examples by hand.
This is a very important step. If you can't compute a couple of solutions by hand,
it's unlikely that you'll be able to write a program that automates the computation.
155
156
Let's assume that a first-class stamp costs 39 cents and the customer inserts $1.00.
That's enough for two stamps (78 cents) but not enough for three stamps ($1.17).
Therefore, the machine returns two first-class stamps and 22 penny stamps.
Search WWH ::




Custom Search