拉风的咖菲猫
如果您只想将值处理为分数,则可以创建一个包含分子和分母字段的分数类。编写加、减、乘和除的方法以及toDouble方法。这样,您可以避免在计算期间浮动。编辑:快速实现,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);
}}}