分數(JAVA自學第三天)

import java.util.Scanner;java

public class Main {函數

    public static void main(String[] args) {this

        Scanner in = new Scanner(System.in);ip

        Fraction a = new Fraction(in.nextInt(), in.nextInt());io

        Fraction b = new Fraction(in.nextInt(),in.nextInt());class

        a.print();import

        b.print();構造函數

        a.plus(b).print();im

        a.multiply(b).plus(new Fraction(5,6)).print();next

        a.print();

        b.print();

        in.close();

    } } class Fraction {     int fenmu = 1;     int fenzi= 0;          //構造函數     Fraction(int a,int b)     {         this.fenmu=b;         this.fenzi=a;     }          double toDoutble()     {         return (double)(fenzi/fenmu);     }          /*最大公約數*/     int maxGYS(int a,int b )     {         int t;         while(true)         {             t = b%a;             if(t == 0) {//System.out.println("最大公約數:"+a);                 break;             }             else             {                 b = a;                 a = t;             }         }         return a;     }          //兩分數相加     Fraction plus(Fraction r)     {         Fraction temp = new Fraction(fenzi,fenmu);         int a=fenmu;         int b = r.fenmu;         int t = maxGYS(a,b);               //算出最大公約數         int minGBS = r.fenmu*fenmu/t;   //算出最小公倍數         temp.fenzi = ((minGBS/temp.fenmu)*fenzi)+((minGBS/r.fenmu)*r.fenzi); //最小公倍數乘以各自的分子而後相加         temp.fenmu = minGBS;          //判斷是否能夠約分         t = maxGYS(temp.fenzi,temp.fenmu);           if(t != 1 )         {             temp.fenzi/=t;             temp.fenmu/=t;         }                  return temp;     }          Fraction multiply(Fraction r)     {         Fraction temp = new Fraction(fenzi, fenmu);         temp.fenmu*=fenmu;         temp.fenzi*=fenzi;         int t = maxGYS(temp.fenmu,temp.fenzi);                  //判斷是否能夠約分         if(t != 1 )         {             temp.fenzi/=t;             temp.fenmu/=t;         }         return temp;     }          void print()     {         if( (fenzi/fenmu) == 1  )         {             System.out.println("1");         }         else         {             int t = maxGYS(fenmu,fenzi);             if(t != 1 )             {                 fenzi/=t;                 fenmu/=t;             }             System.out.println(fenzi+"/"+fenmu);         }     } }

相關文章
相關標籤/搜索