代码之家  ›  专栏  ›  技术社区  ›  Micke

需要Java循环

  •  -1
  • Micke  · 技术社区  · 8 年前

    public static void main(String[] args) {
    
        double a = 10;
        double b = 2;
        double c = 3;
        double avg = (a + b + c)/3;
        double avg1 = (avg + b + c)/3;
        double avg2 = (avg1 + b + c)/3;
        double avg3 = (avg2 + b + c)/3;
        System.out.println(avg+ "\n" + avg1+ "\n"+ avg2 + "\n"+ avg3);
    
    }
    
    4 回复  |  直到 8 年前
        1
  •  2
  •   6006604    8 年前

    在功能上,这相当于您所做的:

    public static void main(String[] args) {
    
        double a = 10;
        double b = 2;
        double c = 3;
        double avg = (a + b + c)/3;
    
        System.out.println(avg);
    
        for (int i=0; i<3; i++) {
            avg = (avg + b + c)/3;
            System.out.println(avg);
        }
    
    }
    

        2
  •  0
  •   Utku Umur AÇIKALIN    8 年前

    如果你是说代码更短,效率更高,你可以这样做。

    public static void main(String[] args) {
        double a = 10;
        double b = 2;
        double c = 3;
    
        for (int i = 0; i < 4; i++) {
            a = (a + b + c) / 3;
            System.out.println(a);
       }
    }
    
        3
  •  0
  •   Bobulous    8 年前

    public static double directlyCalculateWeightedAverage(double a, double b,
            double c) {
        return a / 81 + 40 * b / 81 + 40 * c / 81;
    }
    

    达到这种重新公式是因为 a 在混合中只出现一次,然后除以3 这是81。然后每个 b c b

    b/81 + b/27 + b/9 + b/3
    == b/81 + 3b/81 + 9b/81 + 27b/81
    == 40b/81
    

    被一视同仁。

    a/81 + 40b/81 + 40c/81
    

    假设公式不变,我建议使用这种直接方法,而不是重复计算和循环。

        4
  •  0
  •   Thibault Seisel    8 年前

    迭代方法:for循环

    在您的情况下,您可以编写以下内容:

    double a = 10, b = 2, c = 3;
    double avg = a;
    for (int i = 0; i < 4; i++) {
        avg = (avg + b + c) / 3;
        System.out.println(avg);
    }
    

    这将打印计算的4个第一个结果。 avg 只保留最后的结果,这可能不是你想要的。为了保留每个循环迭代的结果,可以将结果存储在数组中。

    递归方法

    private static double recursiveAvg(double avg, int count) {
        // Always check that the condition for your recursion is valid !
        if (count == 0) {
            return avg;
        }
    
        // Apply your formula
        avg = (avg + 2 + 3) / 3;
    
        // Call the same function with the new avg value, and decrease the iteration count.
        return recursiveAvg(avg, count - 1);
    }
    
    public static void main(String[] args) {
        // Start from a = 10, and repeat the operation 4 times.
        double avg = recursiveAvg(10, 4);
        System.out.println(avg);
    }
    

    注意,大多数程序员更喜欢迭代方法:更易于编写和读取,并且不容易出错。