有理数是能表示为两个整数的比值的数字。
在进行四则运算时,如果我们不希望使用浮点数而损失精度,就可以用有理数来表示,这样的表示是精确的,永不会有舍入误差。
实现有理数的相加/减/乘/除
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,即先写测试用例,一步步来完善代码