# 一、代码

## 1、有理数类的代码

package rational;

public class Rational {
private long numerator;//分子
private long denominator;//分母
public Rational (long numerator,long denominator)//构造函数
{
this.numerator = numerator;
this.denominator = denominator;
}
public long getNumerator() {//获得分子
return numerator;
}
public long getDenominator() {//获得分母
return denominator;
}
long n=this.numerator*r2.denominator+this.denominator*r2.numerator;
long d=this.denominator*r2.denominator;
return new Rational(n,d);
}
public Rational subtract(Rational r2){//减法
long n=this.numerator*r2.denominator-this.denominator*r2.numerator;
long d=this.denominator*r2.denominator;
return new Rational(n,d);
}
public Rational multiply(Rational r2){//乘法
long n=this.numerator*r2.numerator;
long d=this.denominator*r2.denominator;
return new Rational(n,d);
}
public Rational divide(Rational r2){//除法
long n=this.numerator*r2.denominator;
long d=this.denominator*r2.numerator;
return new Rational(n,d);
}
public int compare(Rational r2) {//比较大小
long n=this.numerator*r2.denominator-this.denominator*r2.numerator;
if(n>0)System.out.println("r1>r2");
else if(n<0)System.out.println("r1<r2");
else System.out.println("r1==r2");
return 0;
}
}

## 2、测试代码

package pta;

import rational.Rational;

public class test3 {
public static void main(String[] args) {
Rational r1=new Rational(3,4);
Rational r2=new Rational(1,5);
System.out.println(r1.subtract(r2).getNumerator()+"/"+r1.subtract(r2).getDenominator());
System.out.println(r1.multiply(r2).getNumerator()+"/"+r1.multiply(r2).getDenominator());
System.out.println(r1.divide(r2).getNumerator()+"/"+r1.divide(r2).getDenominator());
r1.compare(r2);
}
}

# 二、讨论

### 2、尝试从代码复用的角度来描述你设计的有理数类

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

posted @ 2020-10-04 01:47  白祁  阅读(92)  评论(0编辑  收藏  举报