class Fraction {
private long numerator;
private long denominator;
public Fraction() {
}
public Fraction(long n, long d) {
setFraction(n, d);
}
public void setNumerator(long n) {
numerator = n;
}
public long getNumerator() {
return numerator;
}
public void setDenominator(long d) {
if (d == 0)
denominator = 1;
else
denominator = d;
}
public long getDenominator() {
return denominator;
}
public void setFraction(long n, long d) {
setNumerator(n);
setDenominator(d);
}
public String toString() {
return numerator + "/" + denominator;
}
public Fraction plus(Fraction f) {
Fraction result = new Fraction();
result.numerator = this.numerator * f.denominator + this.denominator
* f.numerator;
result.denominator = this.denominator * f.denominator;
return result;
}
public Fraction minus(Fraction f) {
Fraction result = new Fraction();
result.numerator = this.numerator * f.denominator - this.denominator
* f.numerator;
result.denominator = this.denominator * f.denominator;
return result;
}
public Fraction multiply(Fraction f) {
Fraction result = new Fraction();
result.numerator = this.numerator * f.numerator;
result.denominator = this.denominator * f.denominator;
return result;
}
public Fraction divide(Fraction f) {
Fraction result = new Fraction();
result.numerator = this.numerator * f.denominator;
result.denominator = this.denominator * f.numerator;
return result;
}
}
public class Exec {
public static void main(String[] args) {
Fraction f1 = new Fraction(2, 3);
Fraction f2 = new Fraction(1, 5);
Fraction f3 = f1.plus(f2);
System.out.println(f3);
f3=f1.minus(f2);
System.out.println(f3);
f3=f1.multiply(f2);
System.out.println(f3);
f3=f1.divide(f2);
System.out.println(f3);
}
}
[此贴子已经被作者于2010-12-12 08:30:16编辑过]