Java program for calculating fractions

后端 未结 3 992
梦如初夏
梦如初夏 2021-01-22 18:06

The purpose of the program is to get two user inputs for a fraction, receive a operator from the user, and then to get two more user inputs for a second fraction. The program mu

3条回答
  •  别那么骄傲
    2021-01-22 18:49

    Maybe you want to enter OOP (object oriented programming):

    Q x = new Q(1, 4);
    Q y = new Q(1, 8);
    Q z = x.plus(y);
    System.out.println("%s + %s = %s%n", x, y, z);
    
    (1 / 4) + (1 / 8) = (3 / 8)
    
    public class Q {
        final int numerator;
        final int denominator;
    
        public Q(int numerator, int denominator) {
            int g = gcd(numerator, denominator);
            this.numerator = numerator / g;
            this.denominator = denominator / g;
        }
    
        @Override
        public String toString() {
            return String.format("(%d / %d)", numerator, denominator);
        }
    
        public Q plus(Q rhs) {
            return new Q(numerator * rhs.denominator + rhs.numerator * denominator,
                denominator * rhs.denominator);
        }
    

提交回复
热议问题