Java 我能';我不明白为什么我的APCS多选书中的代码返回19

Java 我能';我不明白为什么我的APCS多选书中的代码返回19,java,Java,这就是方法和问题: public static int mystery(int n) { if (Math.sqrt(n) > n/4) { return n; } else { return mystery(n-1); } } 调用的结果返回了什么值神秘(21) 正确答案是19,当我把代码放入编译器时,我得到了这个答案,但我还没有弄明白为什么这是正确答案 Math.sqrt(double a); 返回一个双精度 (Any Double) /

这就是方法和问题:

public static int mystery(int n) {
   if (Math.sqrt(n) > n/4) {
      return n;
   } else {
      return mystery(n-1);
   }
}
调用的结果返回了什么值
神秘(21)

正确答案是19,当我把代码放入编译器时,我得到了这个答案,但我还没有弄明白为什么这是正确答案

Math.sqrt(double a);
返回一个双精度

(Any Double) / (Any Integer)
返回整数[向下舍入],而

(Any Double) / (Any Double)
返回一个双精度

(Any Double) / (Any Integer)
问题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;
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;

调试和验证的时间到了。在您的方法中,将
Math.sqrt(n)
的值打印到输出。和
n/4
。和
n-1
。它们都印什么?这种调试可能会导致其他问题(例如“整数除法”的含义)。但是现在你有了你所需要的工具来回答你现在提出的问题。。。您可以在调试器中单步执行代码,观察运行时值,输出有用信息,并准确观察代码正在执行的操作。损失的整数除法。计算每个数字的平方根和每个数字的1/4,并确定
n
的哪个值是sqrt(n)>n/4。理想情况下,这应该在白板上或用笔和纸来完成。@TheHeadRush:
n
已经是一个整数了。不除任何浮点值。将
sqrt(n)
n/4
进行比较,其中
n
为20,然后是19。注意区别。