java how to program 8.15

package multiple;

public class Rational {
    public int numerator,denominator;
    public int gcd (int a,int b) {
        if (b==0) return a;
        else return gcd (b,a%b);
    } 
    public Rational (int n,int d) {
        int c = this.gcd (n,d);
        n/= c; d/=c;
        numerator =n;
        denominator = d;
    }
    public Rational () {
    }
    public void add (int a,int b) {
        int x1 = numerator,x2 = denominator;
        x1 += a;x2 +=b;
        int d = this.gcd (x1,x2);
        x1 /= d;
        x2/=d;
        numerator = x1;
        denominator = x2;
    }
    public void substract (int a,int b) {
        int x1 = numerator,x2 = denominator;
        x1 -= a;x2 -=b;
        int d = this.gcd (x1,x2);
        x1 /= d;
        x2/=d;
        numerator = x1;
        denominator = x2;
    }
    public void multiple (int a,int b) {
        int x1 = numerator,x2 = denominator;
        x1 += a;x2 +=b;
        int d = this.gcd (x1,x2);
        x1 /= d;
        x2/=d;
        numerator = x1;
        denominator = x2;
    }
    public void divide (int a,int b) {
        int x1 = numerator,x2 = denominator;
        x1 += a;x2 +=b;
        int d = this.gcd (x1,x2);
        x1 /= d;
        x2/=d;
        numerator = x1;
        denominator = x2;
    }
    public String toString() {
        return String.format("%d / %d", numerator, denominator);
    }
    public String toStringFloat() {
        float res = (float)numerator/(float)denominator;
        return String.format("%f",res); 
    }

}
package multiple;

public class RationalTest {
    public static void main (String[] args) {
        Rational num = new Rational (2,4);
        System.out.printf ("%d\n",num.numerator);
        System.out.println ("num.denominator");
        System.out.printf ("%s\n",num.toString());
        System.out.printf ("%s\n",num.toStringFloat());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值