Java實現對有理數的加減乘除運算,以及求最大公約數並約分。
文件1:Fraction.java
public class Fraction {
int num;
int den;
}
文件2:Rational.java
public class Rational {
int a;
int b;
Fraction f = new Fraction();
boolean dowhile = true;
public Rational(int a, int b){
//約分
f.num = a;
f.den = b;
doFraction(f);
this.a = f.num;
this.b = f.den;
}
public String toString(){ //轉換成分式
if (a!=b)
return Integer.toString(this.a) + '/' + Integer.toString(this.b);
else
return "1";
}
public Rational add(Rational r){ //加法運算
return new Rational(this.a * r.b + this.b * r.a,this.b * r.b);
}
public Rational subtract(Rational r){ //減法運算
return new Rational(this.a * r.b - this.b * r.a,this.b * r.b);
}
public Rational multiply(Rational r){ //乘法運算
return new Rational(this.a * r.a,this.b * r.b);
}
public Rational divide(Rational r){ //除法運算
return new Rational(this.a * r.b,this.b * r.a);
}
public String cal(){
if (a % b == 0)
return Integer.toString(a/b);
else
return String.valueOf((float)a / (float)b);
}
//約分
public void doFraction(Fraction f){
int subnum = 1;
int min = Math.min(f.num, f.den);
//找出最大公約數
for(int i=2;i<=min;i++){
if((f.num%i==0)&&(f.den%i==0)){
subnum = i;
}
}
f.num = f.num/subnum;
f.den = f.den/subnum;
}
}
文件3:RationalTest.java
public class RationalTest {
public static void main(String[] args){
Rational a = new Rational(2,3);
Rational b = new Rational(3,7);
Rational c = new Rational(5,9);
Rational s = a.add(b).add(c);
System.out.println("Calculate 1: " + a.toString() + " + " + b.toString() + " + " + c.toString() + " = " + s.toString());
System.out.println("Calculate 2: " + a.toString() + " + " + b.toString() + " + " + c.toString() + " = " + s.cal());
Rational i = new Rational(3,4);
Rational j = new Rational(2,3);
Rational k = i.multiply(j);
System.out.println(k.toString() + " --> " + k.cal());
//約分
Rational sum = new Rational(52,68);
System.out.println(sum.toString());
}
}
Output Test Result:
Calculate 1: 2/3 + 3/7 + 5/9 = 104/63
Calculate 2: 2/3 + 3/7 + 5/9 = 1.6507937
1/2 --> 0.5
13/17