Java中的计算区域;操作顺序

问题描述 投票:0回答:1

我正在尝试使用以下公式查找多边形的区域:

面积= 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));

我不清楚我的操作顺序在哪里弄乱了。

java math operator-precedence area
1个回答
0
投票

您没有正确翻译公式。您需要return Math.pow(r, 2) * n * Math.sin(2 * Math.PI / n) / 2;正如Forpas在注释中指出的那样,您缺少2并说Math.sin(Math.PI / n)这与运算顺序无关,因为它们都只是乘法和除法。

© www.soinside.com 2019 - 2024. All rights reserved.