首页 > 解决方案 > 如何在这个平方根程序的打印/数学部分使用计数器控制的迭代

问题描述

我正在考虑在程序中添加一个 while 循环,该循环可能会循环 10 次,而不是编写 10 个 println 语句。但我发现很难,因为 x 的值每次在数学部分都不同。我以前写过这段代码,现在我想缩短它。这是一个平方根查找程序,它使用巴比伦方法来查找 [S > 20 || 之间的整数的平方根。S < 400]

    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 a = S / 2.0;
        double b = S / a;
        double c = a + b;
        double d = 0.5 * c;
        // for x2
        double e = S / d;
        double f = d + e;
        double g = 0.5 * f;
        // for x3
        double h = S / g;
        double i = g + h;
        double j = 0.5 * i;
        // for x4
        double k = S / j;
        double l = j + k;
        double m = 0.5 * l;
        // for x5
        double n = S / m;
        double o = m + n;
        double p = 0.5 * o;
        // for x6
        double q = S / p;
        double r = p + q;
        double s = 0.5 * r;
        // for x7
        double t = S / s;
        double u = s + t;
        double v = 0.5 * u;
        // for x8
        double w = S / v;
        double x = v + w;
        double y = 0.5 * x;
        // for x9
        double z = S / y;
        double aa = y + z;
        double ab = 0.5 * aa;

        System.out.printf("%nx0 = %8.4f ", a);
        System.out.printf("%nx1 = %8.4f ", d);
        System.out.printf("%nx2 = %8.4f ", g);
        System.out.printf("%nx3 = %8.4f ", j);
        System.out.printf("%nx4 = %8.4f ", m);
        System.out.printf("%nx5 = %8.4f ", p);
        System.out.printf("%nx6 = %8.4f ", s);
        System.out.printf("%nx7 = %8.4f ", v);
        System.out.printf("%nx8 = %8.4f ", y);
        System.out.printf("%nx9 = %8.4f ", ab);

    }

标签: javasquare-root

解决方案


您需要做的就是在循环外将 d 设置为 2.0。然后d在循环内代替 2.0 使用。循环索引i也用于在打印时命名迭代 (x0, x1, x2, ...)。

double d = 2.0;        // set d to 2.0 here
for (int i = 0; i < 10; i++) {
    double a = S / d;  // use d here, the modified value will be used again
    double b = S / a;
    double c = a + b;
    d = 0.5 * c;
    System.out.printf("x%d = %8.4f%n", i, a);
}

为输入值 50 打印以下内容

x0 =  25.0000
x1 =   3.7037
x2 =   5.8127
x3 =   6.9374
x4 =   7.0698
x5 =   7.0711
x6 =   7.0711
x7 =   7.0711
x8 =   7.0711
x9 =   7.0711

这是一个练习。将当前计算值与上一个值进行比较。如果它们相等(或它们的差异很小),那么您可以退出循环,因为重复迭代不会大大提高准确性。


推荐阅读