题目:写功能平均计算给定数组中数字的平均值。
测试用例:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
// TODO: Replace examples and use TDD development by writing your own tests
public class SolutionTest {
private static final double DELTA = 1e-15;
@Test
public void testSomething() {
assertEquals(1, Kata.find_average(new int[]{1,1,1}), DELTA);
assertEquals(2, Kata.find_average(new int[]{1, 2, 3}), DELTA);
assertEquals(2.5, Kata.find_average(new int[]{1, 2, 3, 4}), DELTA);
}
}
我答:
public class Kata{
public static double find_average(int[] array){
int sum = 0;
for(int i = 0; i < array.length; i++){
sum += array[i];
}
double ave = (double)sum/array.length;
return ave;
}
}
网上大牛:
public class Kata{
public static double find_average(int[] array){
return java.util.Arrays.stream(array).average().orElse(0);
}
}
思考
似乎java8的stream可以干很多事。