Retain precision with double in Java

前端 未结 22 3137
情歌与酒
情歌与酒 2020-11-21 05:15
public class doublePrecision {
    public static void main(String[] args) {

        double total = 0;
        total += 5.6;
        total += 5.8;
        System.out         


        
22条回答
  •  醉酒成梦
    2020-11-21 06:01

    If you just want to process values as fractions, you can create a Fraction class which holds a numerator and denominator field.

    Write methods for add, subtract, multiply and divide as well as a toDouble method. This way you can avoid floats during calculations.

    EDIT: Quick implementation,

    public class Fraction {
    
    private int numerator;
    private int denominator;
    
    public Fraction(int n, int d){
        numerator = n;
        denominator = d;
    }
    
    public double toDouble(){
        return ((double)numerator)/((double)denominator);
    }
    
    
    public static Fraction add(Fraction a, Fraction b){
        if(a.denominator != b.denominator){
            double aTop = b.denominator * a.numerator;
            double bTop = a.denominator * b.numerator;
            return new Fraction(aTop + bTop, a.denominator * b.denominator);
        }
        else{
            return new Fraction(a.numerator + b.numerator, a.denominator);
        }
    }
    
    public static Fraction divide(Fraction a, Fraction b){
        return new Fraction(a.numerator * b.denominator, a.denominator * b.numerator);
    }
    
    public static Fraction multiply(Fraction a, Fraction b){
        return new Fraction(a.numerator * b.numerator, a.denominator * b.denominator);
    }
    
    public static Fraction subtract(Fraction a, Fraction b){
        if(a.denominator != b.denominator){
            double aTop = b.denominator * a.numerator;
            double bTop = a.denominator * b.numerator;
            return new Fraction(aTop-bTop, a.denominator*b.denominator);
        }
        else{
            return new Fraction(a.numerator - b.numerator, a.denominator);
        }
    }
    
    }
    

提交回复
热议问题