簡體   English   中英

我如何找到 3 個重量(磅、盎司)的最大值和平均值 我有一個比較重量的程序

[英]How do I find the maximum and the average for 3 weights (pounds,ounces) I have a program that compares weights

我需要幫助弄清楚如何找到平均重量和最大重量。 在下方,您將看到我創建的方法模板; 但是,我不知道如何找到最大重量和平均重量。

public static void main(String[] args) {
    Weight weight1 = new Weight(4, 13);
    Weight weight2 = new Weight(4, 1);
    Weight weight3 = new Weight(14, 10); // 14 lbs 10 ounces

    System.out.println(weight1 + ", " + weight2 + ", " + weight3);
    System.out.println("Minimum: " + findMinimum(weight1, weight2, weight3));
    System.out.println("Average: " + findAverage(weight1, weight2, weight3));    
}

private static Weight findMinimum(Weight weight1, Weight weight2, Weight weight3) {
    if(weight1.lessThan(weight2)) {
        if (weight1.lessThan(weight3)) {
            return weight1;
        }
        else {
            return weight3;
        }
    }
    else {
        if(weight2.lessThan(weight3)) {
            return weight2;
        }
        else {
            return weight3;
        }
    }
}

private static Weight findMaximum(Weight weight1, Weight weight2, Weight weight3) {
    
}
    
private static Weight findAverage(Weight weight1, Weight weight2, Weight weight3){
    Weight results=new Weight(0,0);
    results= +weight1;
}

對於min和max,首先創建一個比較Weight的function:

public class WeightComparator implements Comparator<Weight> {
    int compare(Weight w1, Weight w2) {
        // return -1 if w1 is higher
        // return 0 if they are equal
        // return 1 if w2 is higher
    }
}

這樣你就可以開始對你的權重進行排序了。 例如,將它們放在一個集合中並使用排序:

ArrayList<Weight> list = new ArrayList<>();
list.add(new Weight(...));
list.add(new Weight(...));
list.add(new Weight(...));
Collections.sort(list, new WeightComparator());

完成后,最小值是第一個元素,最大值是列表的最后一個元素。

對於平均值,只需將所有元素相加,然后除以它們的個數。

public Weight getAverage(List<Weight> list) {
    int pounds = 0;
    int ounces = 0;

    for (Weight w: list) {
        pounds += w.getPounds();
        ounces += w.getOunces();
    }

    return new Weight(pounds / list.size(), ounces / list.size);
}

你的邏輯應該只是:

findMaximum(w1, w2, w3) {
    if (w1 > w2 and w1 > w3) {
        return w1
    }
    if (w2 > w1 and w2 > w3) {
        return w2
    }
    if (w3 > w1 and w3 > w2) {
        return w3
    }
}


findAverage(w1, w2, w3) {
    return (w1+w2+w3) / 3
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM