面积和周长计算各种形状

时间:2010-12-18 19:11:25

标签: java math

Area of a circle, rectangle, triangle, trapezoid, parallelogram, ellipse, sector.
Perimeter of a rectangle, square

是否有一个提供数学函数的java库来计算上述内容?

4 个答案:

答案 0 :(得分:3)

public double areaOfRectangle(double width, double length) {
  return width*height;
}
public double areaOfCircle(double radius) {
  return Math.PI * radius * radius;
}
public double areaOfTriangle(double a, double b, double c) {
  double s = (a+b+c)/2;
  return Math.sqrt(s * (s-a) * (s-b) * (s-c));
}

自己编码有多难?您真的需要一个库来为您完成吗?

你也可以移植this C code来实现许多形状的面积和周长计算。

答案 1 :(得分:2)

我不建议你使用库来做这样的事情。只需查看每个公式,然后编写每行所需的单行代码。

听起来像是某人经典的第一个面向对象的任务:

package geometry;

public interface Shape
{
    double perimeter();
    double area();
}

class Rectangle implements Shape
{
    private double width;
    private double height;

    Rectangle(double w, double h)
    {
        this.width = w;
        this.height = h;
    }

    public double perimeter()
    { 
        return 2.0*(this.width + this.height);
    }

    public double area()
    { 
        return this.width*this.height;
    }
}

// You get the idea - same for Triangle, Circle, Square with formula changes.

答案 2 :(得分:1)

你要求的唯一非平凡的公式是椭圆的周长。

你需要完整的椭圆积分(google for that),或数值积分,或approximate formulas(基本上,“无限系列2”是你应该使用的那个)

答案 3 :(得分:-1)

对于一般情况,您可以使用蒙特卡罗方法进行近似估计。你需要一个好的随机数发生器。取一个足够大的矩形来包含Shape,并在矩形中获得大量随机点。对于每个,使用包含(double x,double y)来查看该点是否在Shape中。 Shape中的点与矩形中所有点的比率,乘以矩形的面积是Shape区域的估计值。

相关问题