我正在尝试使用以下公式找到多边形的面积:
面积 = r^2 n sin( 2 π / n) / 2
其中n是边数,r是半径。我认为我的代码没有产生正确的结果。如果 n = 6 和 r = 4,我得到的面积为 24。我的代码如下:
import java.math.*;
公共类RegularPolygon {
private int n; // number of vertices
private double r; //radius of the polygon
/**
* This is the full constructor
* @param n is the number of vertices
* @param r is the radius
*/
public RegularPolygon(int n, double r) {
super();
this.n = n;
this.r = r;
}
/**
* default constructor. Sets number of sides and radius to zero
*/
public RegularPolygon() {
super();
this.n = 0;
this.r = 0;
}
//getters and setters for Number of vertices "n" and radius "r".
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
@Override
public String toString() {
return "RegularPolygon [n=" + n + ", r=" + r + "]";
}
public double area(){
float area;
//this method returns the area of the polygon
//Use Math.PI and Math.sin as needed
return area = (float) (Math.pow(r, 2)* n * ( Math.sin(Math.PI / n)/2));
我不清楚我的操作顺序在哪里搞砸了。