为什么跳过我的while循环?

时间:2014-12-07 22:31:00

标签: java while-loop

我认为我的程序正在跳过我的while循环,但我真的不确定究竟发生了什么。该函数应该通过找到GCD然后将分子和分母除以该数来减少分数。

    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循环...它似乎被完全跳过了。有什么建议吗?

1 个答案:

答案 0 :(得分:6)

因为它的条件总是错误的。

在第一行中,您设置c等于ab。所以有两种可能性:

  • 如果c == a,那么a%c将为零。所以while条件是假的。
  • 如果c == b,那么b%c将为零。所以while条件是假的。