有理数类的设计
有理数类的设计
一、有理数类的代码
class Rational{
private int numerator;//分子
private int denominator;//分母
public int getNumerator() {//获取分子
return numerator;
}
public void setNumerator(int numerator) {
this.numerator = numerator;
}
public long getDenominator() {//获取分母
return denominator;
}
public void setDenominator(int denominator) {
this.denominator = denominator;
}
public Rational() {
super();
this.numerator = 0;
this.denominator = 1;
}
public Rational(int numerator, int denominator) {//构造函数
super();
int gcd = gcd(numerator,denominator);
this.numerator = numerator/gcd;
this.denominator = denominator/gcd;
}
private int gcd(int n, int d) {//辗转相除法
int s1 = Math.abs(n);
int s2 = Math.abs(d);
int remander = s1%s2;
while(remander!= 0) {
s1 = s2;
s2 = remander;
remander = s1%s2;
}
return s2;
}
public Rational add(Rational secondRational) {//加法
int n = numerator*secondRational.getDenominator()+denominator*secondRational.getNumerator();
int d = denominator*secondRational.getDenominator();
System.out.println(n+" "+d);
return new Rational(n,d);
}
public Rational subtract(Rational secondRational) {//减法
int n = numerator*secondRational.getDenominator()-denominator*secondRational.getNumerator();
int d = denominator*secondRational.getDenominator();
}
public Rational multiply(Rational secondRational) {//乘法
int n = numerator*secondRational.getNumerator();
int d = denominator*secondRational.getDenominator();
return new Rational(n,d);
}
public Rational divide(Rational secondRational) {//除法
int n = numerator*secondRational.getDenominator();
int d = denominator*secondRational.getNumerator();
return new Rational(n,d);
}
public String toString() {//转化为字符串类型
if(denominator == 1) {
return numerator+"";
}
else {
return numerator+"/"+denominator;
}
}
}
二、测试代码
public class testz{
public static void main(String[] args) {
Rational r1 = new Rational(2,1);
Rational r2 = new Rational(2,3);
System.out.println(r1.toString()+"+"+r2.toString()+"="+(r1.add(r2)).toString());
System.out.println(r1.toString()+"-"+r2.toString()+"="+(r1.subtract(r2)).toString());
System.out.println(r1.toString()+"*"+r2.toString()+"="+(r1.multiply(r2)).toString());
System.out.println(r1.toString()+"/"+r2.toString()+"="+(r1.divide(r2)).toString());
}
}
三、讨论
1、描述怎么与c语言的有理数代码相比较,为什么你设计的类更加面向对象?
c语言会更多考虑面向过程,用什么函数来实现它,过程要怎么样;类中很多已经规定好了,直接调用就行了,更多会思考如何优化对象。
2、别人如何复用你的代码?
导入有理数类的属性。
3、别人的代码是否依赖你的有理数类的属性?当你的有理数类的属性修改时,是否会影响他人调用你有理数类的代码?
依赖,有影响。
4、有理数类的public方法是否设置合适?为什么有的方法设置为private?
publish方法可以被任何成员访问,private方法仅限自己访问。本次设计中private隐藏的是两个数据(long numerator,long denominator)。