java中精确计算的方法

图片说明

原代码:
public class Detec {

public static int i;
double pie=3.14;
private double r,h;
{
    i++;
}
Detec(int r,int h){
    this.r=r;
    this.h=h;
}
public double get_v() {
    return pie*r*r*h;
}
void show_v() {
    System.out.println("v="+get_v());
}
public static void main(String args[]) {
    Detec o1=new Detec(3,4);
    Detec o2=new Detec(8,4);
    Detec o3=new Detec(6,4);
    System.out.println("创建个数:"+Detec.i);
    o1.show_v();
    o2.show_v();
    o3.show_v();
}

}
运行结果不精确,请问怎样才能让他实现精确计算。

浮点数运算使用BigDecimal存储数字并计算。

class Detec{
    public static int i;
    BigDecimal pie= new BigDecimal("3.14");
    private BigDecimal r;
    private BigDecimal h;
    {
        i++;
    }
    Detec(BigDecimal r,BigDecimal h){
        this.r=r;
        this.h=h;
    }
    public BigDecimal get_v() {
        return pie.multiply(r.multiply(r)).multiply(h);
    }
    void show_v() {
        System.out.println("v="+get_v());
    }
    public static void main(String args[]) {
        Detec o1=new Detec(new BigDecimal("3"),new BigDecimal("4"));
        Detec o2=new Detec(new BigDecimal("8"),new BigDecimal("4"));
        Detec o3=new Detec(new BigDecimal("6"),new BigDecimal("4"));
        System.out.println("创建个数:"+Detec.i);
        o1.show_v();
        o2.show_v();
        o3.show_v();
    }
}

https://blog.csdn.net/weixin_40760196/article/details/83412127

用bigdecimal来存储,用里面的函数保留两位