Java Reference
In-Depth Information
System.out.printf("%5d", i * j);
}
System.out.println();
}
This code produces the following output:
123456 789 0
2468 0 2 4 6 8 0
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 0 5 0 5 0 5 0 5 0
6 2 8 4 0 6 2 8 4 0
7 4 1 8 5 2 9 6 3 0
8 6 4 2 0 8 6 4 2 0
9 8 7 6 5 4 3 2 1 0
10
20
30
40
50
60
70
80
90 100
The printf method can also solve the problem with the Roundoff program intro-
duced earlier in this chapter. Fixing the precision of the double value ensures that it
will be rounded to avoid the tiny roundoff mistakes that result from double arith-
metic. Here is the corrected program:
1 // Uses System.out.printf to correct roundoff errors.
2 public class Roundoff2 {
3 public static void main(String[] args) {
4 double n = 1.0;
5 for ( int i = 1; i <= 10; i++) {
6 n += 0.1;
7 System.out.printf("%3.1f\n", n);
8 }
9 }
10 }
The program produces the following output:
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9
2.0
 
Search WWH ::




Custom Search