初识类和对象1:表示分数的类


该表示分数的类在构造对象时接收两个整数分别作为分子和分母,为了便于进行运算,还需要将其进行约分。

import java.util.Scanner;
import java.lang.String;

class Fraction{
    int c;
    int m;
    double dec;
    Fraction(int a, int b){     //构造并约分
        int gcd = Gcd(a,b);
        this.c = a / gcd;
        this.m = b / gcd;
    }

    static int Gcd(int x, int y){
        return y == 0 ? x : Gcd(y, x % y);
    }

    double toDouble(){
        this.dec = (double)(this.c) / (double)(this.m);
        return this.dec;
    }

    public Fraction add(Fraction other){
        int res_c, res_m;
        res_c = other.c * this.m + this.c * other.m;
        res_m = other.m * this.m;
        return new Fraction(res_c,res_m);
    }

    public Fraction multiply(Fraction other){
        int res_c, res_m;
        res_c = other.c * this.c;
        res_m = other.m * this.m;
        return new Fraction(res_c,res_m);
    }

    @Override
    public String toString(){
        if(this.c % this.m == 0){
            return String.valueOf((this.c / this.m));
        }
        else{
            return String.valueOf(this.c) + "/" + String.valueOf(this.m);
        }
    }
}

public  class Main {
    public  static  void  main(String[]  args)  {
        Scanner  sc  =  new  Scanner(System.in);
        int  fz,  fm;
        System.out.println("first  number,fenzi  fenmu");
        fz  =  sc.nextInt();
        fm  =  sc.nextInt();
        Fraction  f1  =  new  Fraction(fz,  fm);
        System.out.println("second  number,fenzi  fenmu");
        fz  =  sc.nextInt();
        fm  =  sc.nextInt();
        Fraction  f2  =  new  Fraction(fz,  fm);
        System.out.println("first  Fraction:"  +  f1);
        System.out.printf("first  output  as  double:%.2f\n",  f1.toDouble());
        System.out.println("second  Fraction:"  +  f2);
        System.out.printf("second  output  as  double:%.2f\n",  f2.toDouble());
        System.out.println("result  of  two  Fraction  add:"  +  f1.add(f2));
        System.out.println("result  of  two  Fraction  multiply:"  +  f1.multiply(f2));
        sc.close();
    }
}

 运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值