有理数类的设计
1.有理数类的代码
public class RationalNumber {
private int numerator;//分子
private int denominator;//分母
public int getNumerator() {//获取分子
return numerator;
}
public int getDenominator() {//获取分母
return denominator;
}
public Rational(int numerator, int denominator) {
int gcd = gcd(numerator,denominator);
this.numerator = ((denominator>0)? 1 : -1)*numerator / gcd;
this.denominator = Math.abs(denominator) / gcd;
}
public static int gcd(int numerator, int denominator) {//求最大公约数
int n = Math.abs(numerator);
int 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 add(RationalNumber first,RationalNumber second) {//加法
int n = first.getNumerator * second.getDenominator + second.getNumerator * first.getDenominator;
int d = first.getDenominator * second.getDenominator;
return new Rational(n,d);
}
public sub(RationalNumber first,RationalNumber second) {//减法
int n = first.getNumerator * second.getDenominator - second.getNumerator * first.getDenominator;
int d = first.getDenominator * second.getDenominator;
return new Rational(n,d);
}
public multiply(RationalNumber first,RationalNumber second) {//乘法
int n = first.getNumerator * second.getNumerator;
int d = first.getDenominator * second.getDenominator;
return new Rational(n,d);
}
public divide(RationalNumber first,RationalNumber second) {//除法
int n = first.getNumerator * second.getDenominator;
int d = first.getDenominator * second.getNumerator;
return new Rational(n,d);
}
public boolean equal(RationalNumber first,RationalNumber second) { //判断是否相等
if ((first.getNumerator == second.getNumerator)&(first.getDenominator == second.getDenominator)) {
return true;
} else {
return false;
}
}
public String toString() {//返回string
return this.numerator + "/" + this.denominator;
}
}
public double doubleValue() {//返回double
return 1.0 * this.numerator / this.denominator;
}
public long longValue() {//返回long
return (long)doubleValue();
}
}
2.测试代码
import java.util.Scanner;
import RationalNumber.RationalNumber;;
public class Test {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(sc.hasNext())
{
int a=sc.nextInt(),b=sc.nextInt(),c=sc.nextInt(),d=sc.nextInt();
Rational R1= new Rational(a,b),R2=new Rational(c,d);
Rational R;
R= R1.add(R1, R2);
System.out.println("加法有理数值是:"+R);
R=R1.sub(R1, R2);
System.out.println("减法有理数值是:"+R);
R=R1.multiply(R1, R2);
System.out.println("乘法有理数值是:"+R);
R=R1.divide(R1, R2);
System.out.println("除法有理数值是:"+R);
if(R1.equal(R1, R2))
System.out.println("相等");
else
System.out.println("不相等");
}
}
}
3.尝试描述怎么与c语言的有理数代码相比较,为什么你设计的类更加面向对象?
c的有理数代码是利用函数从过程去考虑去实现这个功能,设计的类的方法和属性是针对它本身特性来考虑的,以类的形式编写,使用者在使用时只需导入即可,更加的方便。
4.尝试从代码复用的角度来描述你设计的有理数类。
a. 别人如何复用你的代码?
导入对应包中的有理数类
b. 别人的代码是否依赖你的有理数类的属性?当你的有理数类的属性修改时,是否会影响他人调用你有理数类的代码?
依赖,当我的有理数类的属性修改时,会影响他人使用。
c. 有理数类的public方法是否设置合适?为什么有的方法设置为private?
合适,使用public在使用有理数类的方法时能够直接有效的调用,而有的方法可以设置为private来防止使用者对数据进行错误修改。
#####