一个分数类:import java.math.BigInteger;
public class Fraction {
BigInteger numerator, denominator, gcd;
void set(String n, String d) {
numerator = new BigInteger(n);
denominator = new BigInteger(d);
}
void simplify() {
gcd = numerator.gcd(denominator);
numerator = numerator.divide(gcd);
denominator = denominator.divide(gcd);
if (denominator.compareTo(BigInteger.ZERO) < 0) {
numerator = numerator.negate();
denominator = denominator.negate();
}
}
int compareTo(Fraction y) {
Fraction z = this.subtract(y);
return z.numerator.compareTo(BigInteger.ZERO);
}
Fraction abs() {
Fraction z = new Fraction();
if (numerator.compareTo(BigInteger.ZERO) < 0) {
z.numerator = numerator.negate();
} else {
z.numerator = numerator;
}
if (denominator.compareTo(BigInteger.ZERO) < 0) {
z.denominator = denominator.negate();
} else {
z.denominator = denominator;
}
return z;
}
Fraction negate() {
Fraction z = this;
z.numerator = z.numerator.negate();
return z;
}
boolean zero() {
return numerator.compareTo(BigInteger.ZERO) == 0;
}
Fraction add(Fraction y) {
Fraction z = new Fraction();
gcd = denominator.gcd(y.denominator);
z.denominator = denominator.multiply(y.denominator).divide(gcd);
z.numerator = numerator.multiply(z.denominator.divide(denominator)).
add(y.numerator.multiply(z.denominator.divide(y.denominator)));
z.simplify();
return z;
}
Fraction subtract(Fraction y) {
Fraction z = new Fraction();
gcd = denominator.gcd(y.denominator);
z.denominator = denominator.multiply(y.denominator).divide(gcd);
z.numerator = numerator.multiply(z.denominator.divide(denominator)).
subtract(y.numerator.multiply(z.denominator.divide(y.denominator)));
z.simplify();
return z;
}
Fraction multiply(Fraction y) {
Fraction z = new Fraction();
z.numerator = numerator.multiply(y.numerator);
z.denominator = denominator.multiply(y.denominator);
z.simplify();
return z;
}
Fraction divide(Fraction y) {
Fraction z = new Fraction();
z.numerator = numerator.multiply(y.denominator);
z.denominator = denominator.multiply(y.numerator);
z.simplify();
return z;
}
void print() {
if (denominator.compareTo(BigInteger.ONE) != 0) {
System.out.printf("%s/%s", numerator.toString(), denominator.toString());
} else {
System.out.printf("%s", numerator.toString());
}
System.out.println();
}
public static void main(String args[]){
Fraction a=new Fraction();
Fraction b=new Fraction();
Fraction c=new Fraction();
Fraction d=new Fraction();
Fraction e=new Fraction();
a.set("1","2");
b.set("1","5");
c.set("1","55");
d.set("1","110");
e=a.add(b).add(c).add(d);
e.print();
}
}
运行:8/11 |