//有理数类
public class Rational {
//成员变量
private long a;//分子
private long b;//分母
//无参构造器
public Rational() {
}
//最大公约数greatest common divisor
private static long gcd(long x,long y)
{
if(x<0)x=-x;
if(y<0)y=-y;
if(y==0)return x;
if(x==0)return y;
return gcd(y,x%y);
}
//有参构造器//不能让分子分母最后的表达式有公约数
public Rational(long a,long b) {
long k=gcd(a,b);//a和b的最大公约数
a=a/k;b=b/k;
this.a=a;
this.b=b;
}
//相加
//新的有理数对象r1
//r1.a分子,r1.b分母
//原来的有理数对象
//this.a分子 ,this.b分母
// (this.a/this.b)+(r1.a/ra.b)=(this.a*r1.b+this.b*r1.a)/(this.b*r1.b)
public Rational add (Rational r1) {
return new Rational(this.a*r1.b+this.b*r1.a , this.b*r1.b);
}
//multiplication(乘法)
public Rational mul(Rational r1)
{
return new Rational(this.a*r1.a , this.b*r1.b);
}
//subtraction (减法)
public Rational sub(Rational r1)
{
return new Rational(this.a*r1.b-this.b*r1.a , this.b*r1.b);
}
//inverse(反转)
public Rational inverse()
{
return new Rational(this.b,this.a);//分子分母颠倒
}
//division(除法)
public Rational div(Rational r1)
{
return mul(r1.inverse());
}
//重写toString方法
public String toString()
{
if(b==1)
{
return " "+a;
}
else return a+"/"+b;
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
Rational R1=new Rational(1,2);
Rational R2=new Rational(1,4);
Rational R3=R1.add(R2);
Rational R4=R1.div(R2);
System.out.println(R1);
System.out.println(R3);
System.out.println(R4);
}
}
【Java】有理数四则运算
于 2023-01-27 13:30:13 首次发布