【问题标题】:Calculating Area in Java; Order of Operations用Java计算面积;操作顺序
【发布时间】:2020-05-04 17:59:41
【问题描述】:

我正在尝试使用以下公式找到多边形的面积:

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

我不清楚我的操作顺序在哪里搞砸了。

【问题讨论】:

  • 首先,你不需要在你的 area 方法中声明一个新的浮点数。
  • Math.sin(2 * Math.PI / n)
  • @forpas ok,所以应该是 return (float) (Math.pow(r, 2)* n * Math.sin(2 * Math.PI / n));
  • 不要转换为浮动
  • Math.pow(r, 2)* n * Math.sin(2 * Math.PI / n) / 2

标签: java math operator-precedence area


【解决方案1】:

您没有正确翻译公式。你需要return Math.pow(r, 2) * n * Math.sin(2 * Math.PI / n) / 2;正如forpas在cmets中指出的那样,你错过了一个2并说Math.sin(Math.PI / n)这与运算顺序无关,因为它只是乘法和除法。

【讨论】:

    【解决方案2】:

    您不应该将类型转换为 float,因为您已将方法的返回类型声明为 double

    return Math.pow(r,2) * n * Math.sin(2 * Math.PI/n) / 2;
    

    我认为上面的代码会满足你的需要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-12
      • 2011-01-09
      • 2023-01-11
      • 2022-12-11
      • 2018-01-09
      • 2018-04-15
      • 1970-01-01
      相关资源
      最近更新 更多