我想我的程序正在跳過我的while循環,但我實在不確定發生了什麼。該函數應該通過找到GCD然後再除以分子和分母來減少分數。爲什麼我的while循環被跳過?
class Rational {
private int numerator, denominator;
//Constructor
public Rational (int num, int den) {
numerator = num;
denominator = den;
}
//Method for multiplying fractions
public Rational times (Rational that) {
Rational x = new Rational (this.numerator*that.numerator, this.denominator*that.denominator);
x = x.reduce();
return x;
}
//Method for displaying fractions as strings
public String toString() {
return new String(numerator+"/"+denominator);
}
//Method for adding fractions
public Rational plus(Rational that) {
Rational x = new Rational ((this.numerator*that.denominator)+(that.numerator*this.denominator),
this.denominator*that.denominator);
//x = x.reduce();
return x;
}
//Method for subtracting fractions
public Rational minus(Rational that) {
Rational x = new Rational ((this.numerator*that.denominator)-(that.numerator*this.denominator),
this.denominator*that.denominator);
//x = x.reduce();
return x;
}
//Method for dividing fractions
public Rational divideBy(Rational that) {
Rational x = new Rational (this.numerator*that.denominator, this.denominator*that.numerator);
//x = x.reduce();
return x;
}
public Rational reduce() {
int a = Math.abs(this.numerator);
int b = Math.abs(this.denominator);
int c = Math.min(a, b);
System.out.println(c);
System.out.println(a%c);
System.out.println(b%c);
if (a==0) {
return new Rational (0,1);
}
else {
while (((a%c)!= 0) && ((b%c)!= 0)) {
c = c-1;
System.out.println(c);
}
System.out.println(c);
return new Rational (this.numerator/c,this.denominator/c);
}
}
}
public class RationalTester {
public static void main(String[] args) {
Rational x = new Rational (6,4); //The fraction 6/4
Rational y = new Rational (5,2); //The fraction 5/2
Rational z = x.times(y); //Their product
Rational w = x.plus(y); //Their sum
Rational v = x.minus(y); //Their difference
Rational u = x.divideBy(y); //Their quotient
JOptionPane.showMessageDialog(null, x.toString()+" * "+y.toString()+" = "+z.toString());
JOptionPane.showMessageDialog(null, x.toString()+" + "+y.toString()+" = "+w.toString());
JOptionPane.showMessageDialog(null, x.toString()+" - "+y.toString()+" = "+v.toString());
JOptionPane.showMessageDialog(null, x.toString()+"/"+y.toString()+" = "+u.toString());
}
}
我得到的分子和分母的絕對值,以確保如果分數是負的,我會保持,在年底。如果分子是0,我被要求返回(0,1)。問題是關於while循環......它似乎被完全跳過了。有什麼建議麼?
提供一些樣本輸入和期望的輸出用於測試 – 2014-12-07 22:33:47
請給出'a','b'和'c'的示例值...注意,比較浮點數的平等性很少是一個好主意。他們*需要*是'double'而不是'int'嗎?請注意,如果您提供簡短但完整的*程序來證明問題,這將有助於... – 2014-12-07 22:33:50
http://en.wikipedia.org/wiki/Modulo_operation#Common_pitfalls – specializt 2014-12-07 22:35:55