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;
    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);
    }
4

2 回答 2

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();

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

于 2013-04-16T05:07:46.687 回答
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);
于 2013-04-16T05:11:41.653 回答