Java编程算法基础---有理数表示

有理数是能表示为两个整数的比值的数字。

在进行四则运算时,如果我们不希望使用浮点数而损失精度,就可以用有理数来表示,这样的表示是精确的,永不会有舍入误差。


实现有理数的相加/减/乘/除

package NO5;

public class MyRational {
    private int x;
    private int y;
    public MyRational(){
    	
    }
    public MyRational(int x, int y) {
		// TODO Auto-generated constructor stub
      int k;
      if(x < 0)
    	 k = gcd(-x, y);  //因为在做有理数的减法的时候可能出现x<0的情况,此时应该求x的绝对值与y的公约数k
      else 
	     k = gcd(x,y);
	   //System.out.println(k);
       this.x = x / k;   //如果x为正,则约分后的X为正,否则为负
	   this.y = y / k;   //y始终为正数
    }
    public  int gcd(int a,int b){
    	if(b == 0) return a;
    	
    	return gcd(b, a%b);
    	
    }
    public MyRational add(MyRational input){
  	
    	return new MyRational(this.x * input.y + input.x * this.y, 
    			this.y * input.y );
    }
    public MyRational mul(MyRational input){
    	
    	
        return new MyRational(this.x * input.x, this.y * input.y);
    }
    public MyRational div(MyRational input){
    	
    	
    	return  new MyRational(this.x * input.y, this.y * input.x);
    }
    public MyRational sub(MyRational input){
    	
 
    	return  new MyRational(this.x * input.y - this.y * input.x, this.y * input.y);
    }
    
   
    public MyRational(int x) {
		// TODO Auto-generated constructor stub
	   this.x = x; //(x,1);
	   y = 1;
    }
  
    public String toString(){
    	if(y == 1) return x + "";
    	
    	return  x +  "/"  + y;	
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
             //MyRational a = new MyRational(1);
             //System.out.println(a);
             //MyRational a = new MyRational(5, 3);
             MyRational a = new MyRational(0,5);
             //System.out.printn(a);
             MyRational b = new MyRational(2,3);
             //MyRational c = a.sub(b);
             //MyRational c = a.add(b);
             //MyRational c = a.mul(b);
            MyRational c = a.div(b);
             System.out.println(c);
	      
		//System.out.println(-2/5);
	}
	

}
采用的是测试驱动开发模式 TDD,即先写测试用例,一步步来完善代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值