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


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值