java - 对 2 个分数的操作

标签 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;  
          }

最佳答案

尝试将负函数更改为:

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

关于java - 对 2 个分数的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47036483/

相关文章:

java - 上传文件到数据库查毒

java - 使用 Java 从图像文件中提取元数据

java - 是否有类似 ZenTest/Autotest for Java 和 JUnit 的东西

java - 使用数据库访问的 OOP 编程

java - 如何使用不同的参数类型实现一种方法?

oop - 建模和责任

java - 在 Java 中以流形式检索 Redis 值的示例

c++ - 限制对类方法的访问

html - 没有服务器端代码的面向对象的 HTML。可能的?

java - IntelliJ Idea 不更新远程 Tomcat,仅重新部署作品