Java Reference
In-Depth Information
sum += currentValue;
currentValue += 0.01 ;
}
After this loop, sum is 50.50000000000003 . This loop adds the numbers from smallest to
biggest. What happens if you add numbers from biggest to smallest (i.e., 1.0 , 0.99 , 0.98 ,
. . . , 0.02 , 0.01 in this order) as follows:
double currentValue = 1.0 ;
for ( int count = 0 ; count < 100 ; count++) {
sum += currentValue;
currentValue -= 0.01 ;
}
After this loop, sum is 50.49999999999995 . Adding from biggest to smallest is less accurate
than adding from smallest to biggest. This phenomenon is an artifact of the finite-precision arith-
metic. Adding a very small number to a very big number can have no effect if the result requires
more precision than the variable can store. For example, the inaccurate result of 100000000.0
+ 0.000000001 is 100000000.0 . To obtain more accurate results, carefully select the order
of computation. Adding smaller numbers before bigger numbers is one way to minimize errors.
avoiding numeric error
5.8 Case Studies
Loops are fundamental in programming. The ability to write loops is essential in
learning Java programming.
Key
Point
If you can write programs using loops, you know how to program! For this reason, this section
presents four additional examples of solving problems using loops.
5.8.1 Case Study: Finding the Greatest Common Divisor
The greatest common divisor (gcd) of the two integers 4 and 2 is 2 . The greatest common
divisor of the two integers 16 and 24 is 8 . How would you write this program to find the great-
est common divisor? Would you immediately begin to write the code? No. It is important to
think before you code . Thinking enables you to generate a logical solution for the problem
without concern about how to write the code.
Let the two input integers be n1 and n2 . You know that number 1 is a common divisor, but
it may not be the greatest common divisor. So, you can check whether k (for k
gcd
think before you code
2 , 3 , 4 , and
so on) is a common divisor for n1 and n2 , until k is greater than n1 or n2 . Store the common
divisor in a variable named gcd . Initially, gcd is 1 . Whenever a new common divisor is found,
it becomes the new gcd. When you have checked all the possible common divisors from 2 up
to n1 or n2 , the value in variable gcd is the greatest common divisor. Once you have a logical
solution, type the code to translate the solution into a Java program as follows:
=
logical solution
int gcd = 1 ; // Initial gcd is 1
int k = 2 ; // Possible gcd
while (k <= n1 && k <= n2) {
if (n1 % k == 0 && n2 % k == 0 )
gcd = k; // Update gcd
k++; // Next possible gcd
}
// After the loop, gcd is the greatest common divisor for n1 and n2
Listing 5.9 presents the program that prompts the user to enter two positive integers and
finds their greatest common divisor.
 
 
 
Search WWH ::




Custom Search