# 有理数类的设计

## 1.代码

package rational;
public class Rational{
private long numerator = 0;//分子
private long denominator = 1;//分母

public Rational() {//构造函数
this(0,1);
}
public Rational(long numerator, long denominator){
long gcd = gcd(numerator,denominator);
this.numerator = ((denominator>0)? 1 : -1)*numerator / gcd;
this.denominator = Math.abs(denominator) / gcd;
}
public static long gcd(long numerator, long denominator){//求最大公约数方便化简
long n = Math.abs(numerator);
long d = Math.abs(denominator);
int gcd = 1;
for(int i=1;i<=d&&i<=n;i++){
if(n%i==0&&d%i==0)
gcd = i;
}
return gcd;
}
public long getNumerator(){//生成器
return numerator;
}
public long getDenominator(){
return denominator;
}
long n = numerator*secondRational.getDenominator()+denominator*secondRational.getNumerator();
long d = denominator*secondRational.getDenominator();
return new Rational(n,d);
}
public Rational subtract(Rational secondRational){//减法
long n = numerator*secondRational.getDenominator()-denominator*secondRational.getNumerator();
long d = denominator*secondRational.getDenominator();
return new Rational(n,d);
}
public Rational multiply(Rational secondRational){//乘法
long n=numerator*secondRational.getNumerator();
long d=denominator*secondRational.getDenominator();
return new Rational(n,d);
}
public Rational divide(Rational secondRational){//除法
long n = numerator*secondRational.getDenominator();
long d = denominator*secondRational.numerator;
return new Rational(n,d);
}
public boolean equals(Object praml){//判断是否相等
if((this.subtract((Rational)(praml))).getNumerator()==0){
return true;
}
else return false;
}
public int intValue(){//将Rational转化成int
return (int)doubleValue();
}
public float floatValue(){//将Rational转化成float
return (float)doubleValue();
}
public double doubleValue(){//将Rational转化成double
return numerator*1.0/denominator;
}
public long longValue(){//将Rational转化成long
return (long)doubleValue();
}
public String toString(){//toString类
if(denominator==1){
return numerator+"";
}
else return numerator+"/"+denominator;
}
}


## 2.测试代码

package test;

import rational.Rational;

pubilc class Main{
public static void main(String[] args){
Rational test1 = new Rational(1,9);
Rational test2 = new Rational(-4,5);
System.out.println("test1 - test2 = "+test1.substract(test2));
System.out.println("test1 * test2 = "+test1.multiply(test2));
System.out.println("test1 / test2 = "+test1.divide(test2));
System.out.println("test2的int值为"+test2.intValue());
System.out.println("test2的long值为"+test2.longValue());
System.out.println("test2的float值为"+test2.floatValue());
System.out.println("test2的double值为"+test2.doubleValue());
System.out.println("test2的String值为"+test2.toString());
}
}


## 6.有理数类的public方法是否设置合适?为什么有的方法设置为private?

### 因为其中的一些方法需要可以被使用，所以设置为pubilc方法合适。有的方法设置为private，别的类就不能访问该成员变量，而只能通过该类的方法（该方法要求是public的）访问该成员变量，这样就达到了对数据最高级别保护的目的。

posted @ 2020-10-03 20:58  hhs(黄鸿森)  阅读(120)  评论(0编辑  收藏  举报