对2个分数进行操作

时间:2017-10-31 13:19:55

标签: java oop

我正在编写有关Java OOP的作业代码。我必须对2个分数进行操作,但大多数时候输出是错误的,我不知道为什么。我认为简化存在问题,因为结果是正确的,没有简化 如果两个分数0/8和6/14减法应为-3/7但输出为0/1 谢谢您的帮助 ! 以下是代码:

 class Fraction {


          private int numer, denom;


          public Fraction(int numerator, int denominator) {
            numer = numerator;
            denom = denominator;
          }


          private int euclidGcd(int a, int b) {

            int remainder;
            while (b > 0) {
              remainder = a % b;
              a = b;
              b = remainder;
            }   
            return a;
          }


          private Fraction simplify() {

            int gcd = euclidGcd(numer, denom);
            this.numer = this.numer / gcd;
            this.denom = this.denom / gcd;

            Fraction result = new Fraction(numer, denom);  


            return result;  
          }


          public Fraction add(Fraction another) {

            int b = this.denom * another.denom;
            int a = (b/this.denom) * this.numer + (b/another.denom) * another.numer;
            Fraction result = new Fraction(a, b);  
            result.simplify();

            return result;  
          }


          public Fraction minus(Fraction another) {
            int b = this.denom * another.denom;
            int a = (b/this.denom) * this.numer - (b/another.denom) * another.numer;

            Fraction result = new Fraction(a, b);  // stub
            result.simplify();

            return result;  
          }


          public Fraction times(Fraction another) {
            int a = this.numer * another.numer;
            int b = this.denom * another.denom;

            Fraction result = new Fraction(a, b);  // stub
            result.simplify();

            return result;  
          }

          public Fraction divide(Fraction another) {
            int a = this.numer * another.denom;
            int b = this.denom * another.numer;
            Fraction result = new Fraction(a, b);  // stub

            result.simplify();
            return result;  
          }


          public String toString() {
            return numer + "/" + denom;  
          }

1 个答案:

答案 0 :(得分:1)

尝试将减号功能更改为:

public Fraction minus(Fraction another) {
    return new Fraction(this.numer * another.denom - another.numer * this.denom, this.denom * other.denom).simplify();
}