日期:2014-05-20 浏览次数:20632 次
public class Fraction {
private int numerator;
private int denominator;
public Fraction(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
public int getNumerator() {
return numerator;
}
public void setNumerator(int numerator) {
this.numerator = numerator;
}
public int getDenominator() {
return denominator;
}
public void setDenominator(int denominator) {
this.denominator = denominator;
}
public Fraction add(Fraction summand) {
if (this.denominator % summand.getDenominator() == 0) {
summand.setNumerator(summand.getNumerator() * (this.denominator / summand.getDenominator()));
summand.setDenominator(this.denominator);
} else if (summand.getDenominator() % this.denominator == 0) {
this.setNumerator(summand.numerator * (summand.getDenominator() / this.denominator));
this.setDenominator(summand.denominator);
} else {
int tmp = this.denominator;
this.setDenominator(this.denominator * summand.getDenominator());
this.setNumerator(this.numerator * summand.getDenominator());
summand.setDenominator(tmp * summand.getDenominator());
summand.setNumerator(tmp * summand.getNumerator());
}
return new Fraction(this.numerator + summand.getNumerator(), this.denominator);
}
@Override
public String toString() {
if (this.numerator % this.denominator == 0) {
return "" + this.numerator / this.denominator;
} else if (this.denominator % this.numerator == 0) {
return 1 + "/" + this.denominator / this.numerator;
} else {