CSC300 / CSC402: A bad solution [12/20] |
01 |
package algs11; import stdlib.*; public class PlaygroundMax { public static double max (double[] a) { if (a.length == 0) { return 0; } double m = a[0]; for (int i = 1; i < a.length; i++) { if (m < a[i]) { m = a[i]; } } return m; } public static void testMax (double expected, double[] a) { double actual = max (a); if (expected != actual) { StdOut.format ("max failed: Expecting [%d] Actual [%d] with argument %s\n", expected, actual, java.util.Arrays.toString(a)); } } public static void main (String[] args) { testMax(31, new double[] { 11, 21, 31 }); testMax(31, new double[] { 11, 31, 21 }); testMax(31, new double[] { 31, 11, 21 }); testMax(21, new double[] { 21, 11 }); testMax(21, new double[] { 11, 21 }); testMax(11, new double[] { 11 }); testMax(0, new double[] { }); StdOut.println ("Finished tests"); } } |
0 is a magic number: it is completely arbitrary
Magic numbers are bad
{ }
and { 0 }
have the same max?
Double.NEGATIVE_INFINITY
instead of 0. This makes mathematical sense