首页 > 代码库 > 分数计算

分数计算

import java.util.Scanner;public class test{    public static void main(String args[]){        Rational a=new Rational(4,5);        Rational b=new Rational(3,2);        Rational c=a.chu(b);        c.show();    }}class Rational{    int fenzi=1;    int fenmu=1;    int f(int a,int b){//公约数        if(b>a){            int c=a;            a=b;            b=c;        }//        System.out.println(a);        int c=a%b;        for(;c!=0;c=a%b){            a=b;            b=c;        }        return b;        }    Rational(int a,int b){        int c=f(Math.abs(a),Math.abs(b));        fenzi=a/c;        fenmu=b/c;        System.out.println(c);    }    Rational jia(Rational r){        int a=fenzi*r.fenmu+r.fenzi*fenmu;        int b=fenmu*r.fenmu;//        System.out.println(b);        Rational c=new Rational(a,b);        return c;    }    Rational jian(Rational r){        int a=fenzi*r.fenmu-r.fenzi*fenmu;        int b=fenmu*r.fenmu;//        System.out.println(b);        Rational c=new Rational(a,b);        return c;    }    Rational cheng(Rational r){        int a=fenzi*r.fenzi;        int b=fenmu*r.fenmu;        Rational c=new Rational(a,b);        return c;    }    Rational chu(Rational r){        int a=fenzi*r.fenmu;        int b=fenmu*r.fenzi;        Rational c=new Rational(a,b);        return c;    }    void show(){        System.out.println(fenzi+"/"+fenmu);    }}

 

分数计算