JAVA 分數類

Description
設計一個分數類,分數的分子和分母用兩個整型數表示,類中定義方法能夠對分數進行加法、減法、乘法和除法運算。定義分數類的對象,進行運算並輸出結果。
Input

輸入不定組數的多組數據,每組一行,一行中第一個數據是字符串,"ADD"表示分數相加,"SUB"表示相減,"MUL"表示相乘,"DIV"表示相除。 然後是第一個分數的分子、分母,然後是第二個分數的分子和分母。中間用空格分隔。

Output
針對每組輸入,有一行輸出,第一個爲運算後的分數的分子,第二個爲分母。  要求:分子和分母要互質,如果是整數,分母爲1 。中間用'/'分隔。參見樣例
Sample Input

ADD 1 2 1 3

SUB 1 2 1 3

MUL 1 2 1 3  

DIV 1 2 1 3

SUB 2 3 1 3


Sample Output

5/6

1/6

1/6

3/2

1/3

import java.*;
import java.util.Scanner;
class Fenshu {  
private long molecular;// 分子  
private long denominator;// 分母  

public long getMolecular() {  
return molecular;  
}  
public long getDenominator() {  
return denominator;  
}  
public Fenshu(long molecular, long denominator) {  
this.molecular = molecular;  
if (denominator == 0) {  
System.out.print("分母不能爲零");  
} else {  
this.denominator = denominator;  
}  
gaibian();  
}    
private Fenshu gaibian() {  
long gcd = this.gYueShu(this.molecular, this.denominator);  
this.molecular /= gcd;  
this.denominator /= gcd;  
return this;  
}  
private static long gYueShu(long a, long b) {  
while (b != 0) {  
long temp = a % b;  
a = b;  
b = temp;  
}  
long gyueshu = a;  
return gyueshu;  
}   
public Fenshu ADD(Fenshu fenShu) {   
return new Fenshu(this.molecular * fenShu.denominator + fenShu.molecular * this.denominator, this.denominator * fenShu.denominator);  
}  


public Fenshu SUB(Fenshu fenShu) {  
return new Fenshu(this.molecular * fenShu.denominator - fenShu.molecular * this.denominator, this.denominator * fenShu.denominator);  
}  


public Fenshu MUL(Fenshu fenShu) {  
return new Fenshu(this.molecular * fenShu.molecular, this.denominator * fenShu.denominator);  
}  

public Fenshu DIV(Fenshu fenShu){  
return new Fenshu(this.molecular*fenShu.denominator, this.denominator*fenShu.molecular);  

}  

public String toString() {  
return molecular + "/" + denominator; 

}
public class Main {
public static void main(String agrs[])
{
Scanner cin = new Scanner(System.in);
while(cin.hasNext())
{
int a,b,c,d;
String x;
x=cin.next();
a=cin.nextInt();
b=cin.nextInt();
c=cin.nextInt();
d=cin.nextInt();
Fenshu s1 = new Fenshu(a,b);
Fenshu s2 = new Fenshu(c,d);
if(x.charAt(0)=='A')
{
System.out.println(s1.ADD(s2));
}
if(x.charAt(0)=='S')
{
System.out.println(s1.SUB(s2));
}
if(x.charAt(0)=='M')
{
System.out.println(s1.MUL(s2));
}
if(x.charAt(0)=='D')
{
System.out.println(s1.DIV(s2));
}
}
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章