所以这里是方法和问题:
public static int mystery(int n) {
if (Math.sqrt(n) > n/4) {
return n;
} else {
return mystery(n-1);
}
}
调用结果返回什么值mystery(21)
?
正确答案是 19,当我将代码放入编译器时,我得到了这个答案,但我不知道为什么这是正确答案。
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;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句