如何在巴比伦法求平方根的Java程序中使用计数器控制迭代精简代码
优化实现方案
巴比伦法每轮迭代的计算逻辑固定为 nextX = (currentX + S / currentX) / 2,不需要为每轮迭代单独定义变量,直接通过while计数器控制迭代次数、复用同一个变量存储当前近似值即可,优化后代码如下:
import java.util.Scanner; public class BabylonSquareRoot { public static void main(String[] args) { Scanner myInput = new Scanner(System.in); int S; System.out.print("Enter an integer, S: "); S = myInput.nextInt(); if (S < 0) { System.out.println("This program can not take the square root of a negative number."); } else if (S < 20 || S > 400) { System.out.println("This value is out of range."); } else { double currentX = S / 2.0; int counter = 0; // 打印初始值x0 System.out.printf("%nx%d = %8.4f ", counter, currentX); counter++; // while计数器控制9次迭代,得到x1到x9 while (counter < 10) { // 执行巴比伦迭代公式 currentX = (currentX + S / currentX) / 2; System.out.printf("%nx%d = %8.4f ", counter, currentX); counter++; } } myInput.close(); } }
改动说明
- 仅用
currentX一个变量存储迭代过程中的近似值,不需要声明大量一次性中间变量 - 迭代计算和打印逻辑都整合到while循环中,代码精简度大幅提升,后续如果要调整迭代次数只需要修改循环判断条件即可
- 输出结果和原有手写10次迭代的代码完全一致
内容的提问来源于stack exchange,提问作者king
相关产品推荐
相关产品推荐

