矩形区域的平均值

时间:2013-04-16 05:04:18

标签: java average area

我必须找到每个矩形区域的平均总和。我可以找到每个矩形的区域,我应该将每个区域存储到一个数组中并通过它找到平均值吗?或者那是不可能的?

ArrayList<Rectangle> list = new ArrayList<Rectangle>();
    list.add(new Rectangle(0, 0, 25, 50));
    list.add(new Rectangle(0, 0, 10, 30));
    list.add(new Rectangle(0, 0, 100, 40));
    list.add(new Rectangle(0, 0, 40, 45 ));
    list.add(new Rectangle(0, 0, 13, 13));

    double aAvg = 0.0;
    for (int i = 0; i < list.size(); i++ ) {
        double h = list.get(i).getHeight();
        double w = list.get(i).getWidth();
        double area = h * w;
        System.out.println(area);
    }

2 个答案:

答案 0 :(得分:1)

基本上,你只需要将每个区域加在一起

double sum = 0.0;
for (int i = 0; i < list.size(); i++ ) {
    double h = list.get(i).getHeight();
    double w = list.get(i).getWidth();
    double area = h * w;
    sum += area;
}

然后根据该值计算平均值......

double aAvg = sum / (double)list.size();

除非您需要区域列表,否则不需要维护另一个列表。更简单(更安全)计算它(在这种情况下)......

答案 1 :(得分:0)

试试这个。

ArrayList<Rectangle> list = new ArrayList<Rectangle>();
    list.add(new Rectangle(0, 0, 25, 50));
    list.add(new Rectangle(0, 0, 10, 30));
    list.add(new Rectangle(0, 0, 100, 40));
    list.add(new Rectangle(0, 0, 40, 45 ));
    list.add(new Rectangle(0, 0, 13, 13));

    double aAvg = 0.0;
    double totalArea = 0.0;
    for (int i = 0; i < list.size(); i++ ) {
        double h = list.get(i).getHeight();
        double w = list.get(i).getWidth();
        double area = h * w;
        totalArea += area;
        System.out.println(area);
    }
    aAvg = totalArea / list.size();

    System.out.println("Average area : " + aAvg);