自定义浮点数类(分数形式)

我们可以通过自定义分数类,来解决浮点数数字不准确的问题。

 

class Rational{
	private long _a;//分子
	private long _b;//分母
	
	public Rational() {
		_a=1; 
		_b=1;
	}
	
	//最大公约数
	private static long _gcd(long x, long y) {
		if (x<0) x= -x;
		if (y<0) y= -y;
		if (y==0) return x;
		return _gcd(y, x%y);
	}
	public Rational(long a, long b) {
		long d = _gcd(a, b);
		_a = a/d;
		_b = b/d;
	}
	public Rational add(Rational x) {
		return new Rational(this._a * x._b + this._b * x._a, _b * x._b);
	}
	public Rational mul(Rational x) {
		return new Rational(this._a * x._a, this._b * x._b);
	}
	public Rational negative() {
		return new Rational(-this._a, this._b);
	}
	public Rational sub(Rational x) {
		return this.add(this.negative());
	}
	public Rational inverse() {
		return new Rational(this._b, this._a);
	}
	public Rational div(Rational x) {
		return this.mul(this.inverse());
	}
	public String toString() {
		if (_b==1)
			return " " + _a;
		else
			return _a + "/" + _b;
	}
	
	
}

public class Main{
	//自定义浮点数表示方法
	public static void main(String[] args) {
		Rational a = new Rational(5, 1);
		Rational b = new Rational(1, 15);
		Rational c = a.add(b);
		Rational d = a.div(b);
		System.out.println(a);
		System.out.println(c);
		System.out.println(d);
	}
	
}

 

这里面有一个求最大公约数的方法,使用的是递归形式的辗转相除法。因为分母一般化为最简分数比的形式。还有就是这里面的加减乘除的写法也是很有意思的。最后不要忘记重写to_string方法。不然不能输出结果。

 

 

 

 

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值