以下是可能包含问题的代码部分。这是我的班级。
private int GCD(int Num, int Denom)
{
int gcd;
gcd = Num % Denom;
if(gcd == 0)
return Denom;
else
{
return GCD(Denom, gcd);
}
}
public Fractions add(Fractions frac)
{
Fractions newFrac = new Fractions();
this.Num = this.Num * frac.Denom;
this.Denom = this.Denom * frac.Denom;
frac.Num = frac.Num * this.Denom;
frac.Denom = frac.Denom * this.Denom;
frac.Denom = this.Denom;
newFrac.Denom = frac.Denom;
newFrac.Num = this.Num + frac.Num;
Denom = GCD(newFrac.Num, newFrac.Denom);
if (Denom == 0)
return newFrac;
else
{
newFrac.Num = newFrac.Num / Denom;
newFrac.Denom = newFrac.Denom / Denom;
return newFrac;
}
}
这是我为它写的小型演示代码。请帮我找到问题所在。
public class FractionsDemo
{
public static void main(String [] args)
{
Fractions frac1 = new Fractions();
Fractions frac2 = new Fractions();
Fractions frac3 = new Fractions();
frac1.read();
frac2.read();
System.out.println("The first fraction is " + frac1.Num + "/" + frac1.Denom);
System.out.println("The second fraction is " + frac2.Num +"/" + frac2.Denom);
frac3 = frac1.add(frac2);
System.out.println("adding the first and second results in " + frac3.Num + "/" + frac3.Denom );
}
}
正如我在标题中提到的,我的代码不会显示任何错误。问题是一个逻辑问题。非常感谢您的帮助。另外,请尝试解释您的解决方案的原因。提前致谢。
答案 0 :(得分:0)
问题出在这里
this.Denom = this.Denom * frac.Denom;
frac.Num = frac.Num * this.Denom;
您在设置frac.Num之前设置此.Denom,您必须将订单切换到
frac.Num = frac.Num * this.Denom;
this.Denom = this.Denom * frac.Denom;