Java有理数的四则运算

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

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/05a63ffeda007f2edffdf7fbb709e24c.html