// Ian! D. Allen - idallen@idallen.ca - www.idallen.com // FunnyMath4 - wrong answers from simple arithmetic // Compile and run this program. // Explain why some of the outputs are incorrect. public class FunnyMath4 { public static void main(String[] args) { int n = 25; double x; System.out.println("Add up increasing numbers of tenths"); System.out.printf("%2s %3s %3s %20s %20s\n", "i", "10i", "cou", "xprev", "x"); System.out.printf("%2s %3s %3s %20s %20s\n", "--", "---", "---", "-------------------", "-------------------"); for (int i = 0; i < n; i++) { int counter = 0; double xprevious = 0.0; for (x = 0.0; x < i; x += 0.1) { counter++; xprevious = x; } System.out.printf("%2d %3d %3d %20.17f %20.17f", i, (10*i), counter, xprevious, x ); // we should have looped 10*i times to increment counter if ( 10*i != counter ) { System.out.print(" *** ERROR ***" ); } System.out.println(""); } } } /* OUTPUT Add up increasing numbers of tenths i 10i cou xprev x -- --- --- ------------------- ------------------- 0 0 0 0.00000000000000000 0.00000000000000000 1 10 11 0.99999999999999990 1.09999999999999990 *** ERROR *** 2 20 20 1.90000000000000060 2.00000000000000040 3 30 30 2.90000000000000120 3.00000000000000130 4 40 40 3.90000000000000200 4.00000000000000200 5 50 51 4.99999999999999800 5.09999999999999800 *** ERROR *** 6 60 61 5.99999999999999500 6.09999999999999400 *** ERROR *** 7 70 71 6.99999999999999100 7.09999999999999100 *** ERROR *** 8 80 81 7.99999999999998800 8.09999999999998700 *** ERROR *** 9 90 91 8.99999999999998400 9.09999999999998400 *** ERROR *** 10 100 101 9.99999999999998000 10.09999999999998000 *** ERROR *** 11 110 111 10.99999999999997700 11.09999999999997700 *** ERROR *** 12 120 121 11.99999999999997300 12.09999999999997300 *** ERROR *** 13 130 131 12.99999999999997000 13.09999999999997000 *** ERROR *** 14 140 141 13.99999999999996600 14.09999999999996600 *** ERROR *** 15 150 151 14.99999999999996300 15.09999999999996200 *** ERROR *** 16 160 161 15.99999999999996000 16.09999999999996000 *** ERROR *** 17 170 171 16.99999999999997000 17.09999999999997300 *** ERROR *** 18 180 181 17.99999999999998600 18.09999999999998700 *** ERROR *** 19 190 190 18.90000000000000000 19.00000000000000000 20 200 200 19.90000000000001300 20.00000000000001400 21 210 210 20.90000000000002700 21.00000000000003000 22 220 220 21.90000000000004000 22.00000000000004300 23 230 230 22.90000000000005500 23.00000000000005700 24 240 240 23.90000000000007000 24.00000000000007000 */