这是方法和问题:
public static int mystery(int n) {
if (Math.sqrt(n) > n/4) {
return n;
} else {
return mystery(n-1);
}
}
调用mystery(21)
返回什么值?
正确的答案是19,当我将代码放入编译器时我得到了这个答案,但是我还没有弄清楚为什么这是正确的答案。
答案 0 :(得分:0)
Math.sqrt(double a);
返回双精度值。
(Any Double) / (Any Integer)
返回整数[向下舍入],而
(Any Double) / (Any Double)
返回双精度值。
问题1:
Math.sqrt(21) == 4.58257569496;
21 / 4 == 5;
Math.sqrt(21) < 21 / 4;
//(Then it returns Mystery(n-1))
Math.sqrt(20) == 4.472135955;
20 / 4 == 5;
Math.sqrt(20) < 20 / 4;
//Then it returns Mystery(n-1)
Math.sqrt(19) == 4.35889894354;
19 / 4 == 4;
Math.sqrt(19) > 19 / 4;
returns 19;
问题2:
Math.sqrt(19) == 4.35889894354.
19 / 4 == 4
//It would be 4.75, **but** java rounds down to the nearest Integer, but it ALWAYS rounds down.
//To stop this, the condition Math.sqrt(n) > n/4;
//Would become Math.sqrt(n) > n/4.0;