我用下面的公式实现了方法来逼近数的平方根:nextGuess = (lastGuess + n / lastGuess) / 2;因此,当n和nextGuess几乎相同时,lasGuess是近似平方根。我所做的是检查nextGuess和nextGuess小于非常小的数,例如lastGuess,然后我可以说0.0001是nextGuess的近似平方根。如果不n就变成nextGuess。那么,我如何才能以正确的方式实现这一点呢?我的当前代码:public static void getApproximatedSquare(long n){ DecimalFormat decimalFormat = new DecimalFormat("#.####"); decimalFormat.setRoundingMode(RoundingMode.CEILING); double lastGuess = 1, nextGuess; nextGuess = (lastGuess + n / lastGuess) / 2; Double init = 0.0001; System.out.println(decimalFormat.format(init)); if (Double.valueOf(decimalFormat.format(nextGuess)) <= init) //todo} (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 目前的执行草案有几个缺陷:我怀疑你真的需要,它只是从结果中去除了一些精度你的收敛条件不是Double.valueOf(decimalFormat.format(...))而是nextGuess < init你必须重复这个近似直到收敛,所以你不能只使用一个difference_between_nextGuess_and_lastGuess < init。您需要if或for或(在我的解决方案中)while这应该有效(在每一步,它都会打印最后和下一个猜测)public static double getApproximatedSquare(long n) { DecimalFormat decimalFormat = new DecimalFormat("#.####"); decimalFormat.setRoundingMode(RoundingMode.CEILING); double lastGuess, nextGuess = 1; double init = 0.0001; do { lastGuess = nextGuess; nextGuess = (lastGuess + (double) n / lastGuess) / 2; System.out.println(decimalFormat.format(lastGuess)+" ---> "+decimalFormat.format(nextGuess)); } while (Math.abs(lastGuess - nextGuess) >= init); return nextGuess;} (adsbygoogle = window.adsbygoogle || []).push({}); 08-06 12:22