为什么我的getFloat()中的float值变为0.0?

时间:2018-08-31 17:10:36

标签: floating-point getter-setter volume pi main-method

我是Java新手,关于float的编码是否有问题?因为它变成了0.0,而我对浮动不甚了解,您能解释一下吗?它发生在getFloat

该程序用于计算圆锥体体积

public class Cone_Volume
{
private int ri, hi, ivol;
private float rf, hf, fvol;

public Cone_Volume()
{

}

public Cone_Volume(int ri, int hi)
{
    this.ri = ri;
    this.hi = hi;
}

public Cone_Volume(float rf, float hf)
{
    this.rf = rf;
    this.hf = hf;
}

public int getInt()
{
    int ivol = (int)((3.142f*(ri*ri)*hi)/3);
    return ivol;
}

public float getFloat()
{
    float fvol = (float)((3.142f*(ri*ri)*hi)/3);
    return fvol;
}

public void Volume_I(int ri, int hi)
{
    this.ri = ri;
    this.hi = hi;
}

public void Volume_F(float rf, float hf)
{
    this.rf = rf;
    this.hf = hf;
}
}

该程序用于Cone_Volume的主要方法

public class TestConeVol
{
public static void main(String args[])
{
    Cone_Volume cone1 = new Cone_Volume (5,10);
    Cone_Volume cone2 = new Cone_Volume (3.5f,7.9f);
    Cone_Volume cone3 = new Cone_Volume ();
    Cone_Volume cone4 = new Cone_Volume ();

    cone3.Volume_I (10,30);
    cone4.Volume_F (9.4f,5.8f);

    System.out.println("Volume of cone one : " + cone1.getInt());
    System.out.println("Volume of cone two : " + cone2.getFloat());
    System.out.println("Volume of cone three : " + cone3.getInt());
    System.out.println("Volume of cone four : " + cone4.getFloat());
}
}

输出:

Volume of cone one : 261

Volume of cone two : 0.0

Volume of cone three : 3141

Volume of cone four : 0.0

1 个答案:

答案 0 :(得分:0)

在方法getFloat中,您分别错误地使用了rihi而不是rfhf

这里重要的一课是使用有意义的名称;)