gpt4 book ai didi

java - 为什么我的 while 循环被跳过?

转载 作者:行者123 更新时间:2023-12-01 07:58:20 24 4
gpt4 key购买 nike

我认为我的程序正在跳过 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 循环...似乎它被完全跳过。有什么建议吗?

最佳答案

因为它的条件总是假的。

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

  • 如果c == a,则a%c将为零。所以 while 条件为 false。
  • 如果c == b,则b%c将为零。所以 while 条件为 false。

关于java - 为什么我的 while 循环被跳过?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27348662/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com