如何在java中使用float计算分数

时间:2017-07-21 08:42:36

标签: java encapsulation getter-setter fractions

我的花车有问题。我的第一个问题是我的公共浮点区域(),问题是结果值返回零。第二个是public float computeHeight(),没有值会返回。我对此感到头痛。请帮帮我谢谢。只要删除重复或重新发布。谢谢

private int sideA, sideB, sideC;
private float computePerimeter;
private float area;
private float computeHeight;

public Triangle(){
}

// I want to set all sides to 10

public Triangle(int a, int b, int c){
    sideA = a;
    sideB = b;
    sideC = c;
}

//setters & getters

//perimeter is the sum of all the sides of the triangle.
public float computePerimeter(){
    computePerimeter = sideA + sideB + sideC;
    return computePerimeter;
}


//A=1/2bh.
//A = Area of the triangle
//b = Length of the base of the triangle //SideB
//h = Height of the base of the triangle //SideA

public float area(){
     area =   1/2 * (sideB  * sideA);
     return area;
}

public float computeHeight(){
     sideC = 2 * (area/sideB) ;
     return computeHeight;
}


public void display(){
        System.out.println("Side A: "+getSideA() +" Side B: "+getSideB()+" Side C: "+getSideC() );
        System.out.println("\nThe sum of all the sides of the triangle is: " +computePerimeter() );
        System.out.println("The area of the triangle is: " + area() );
}

public static void main(String []args){
    Triangle result = new Triangle();
    result.setSideA(10);
    result.setSideB(10);
    result.setSideC(10);
    result.display();

}

2 个答案:

答案 0 :(得分:0)

也许:

public float area(){
  area =  (float) (0.5f * (sideB * sideA));
  return area;
}

public float computeHeight(){
  sideC = 2f * (area/sideB) ;
  return computeHeight;
}

添加" f"并且铸件使得数字被视为浮点数。

相关:I don't know how to cast to float in Java

如果你不这样做,那么这个数字就像是一个整数(整数世界的1/2 = 0)一样被处理。因此,你会失去很多精确度。

答案 1 :(得分:0)

1/2返回0,因为它们是int,您需要使用(1.0 / 2)

另外,我建议您将所有floatint替换为double(对于6个属性),它会让您没有警告possible loss convertion' to avoid casting(浮动) )and use f`在数字

之后
private double sideA, sideB, sideC, computePerimeter, area, computeHeight;

我将向您学习一个技巧,这将把结果分配给area并返回它:

public double area() {
     return (area = 1.0 / 2 * (sideB * sideA));
}

最后一件事,因为你有一个public Triangle(double a, double b, double c)构造函数,你可以替换

Triangle result = new Triangle();
result.setSideA(10);
result.setSideB(10);
result.setSideC(10);

单行<{1}}