标签:
要实现Rational类的加减乘除,要实现其可比较性,要覆盖toString()方法,要实现不同数据类型的转换等。
1 package chapter14; 2 3 public class Rational extends Number implements Comparable { 4 private long numerator=0; 5 private long denominator=1; 6 7 public Rational(){ 8 this(0,1); 9 } 10 public Rational(long numerator, long denominator) { 11 // TODO Auto-generated constructor stub 12 long gcd=gcd(numerator,denominator); 13 this.numerator=((denominator>0)?1:-1)*numerator/gcd; 14 this.denominator=Math.abs(denominator)/gcd; 15 } 16 17 private static long gcd(long n, long d) { 18 // TODO Auto-generated method stub 19 long n1=Math.abs(n); 20 long n2=Math.abs(d); 21 int gcd=1; 22 23 for(int k=1;k<=n1&&k<=n2;k++){ 24 if(n1%k==0&&n2%k==0) 25 gcd=k; 26 } 27 return gcd; 28 } 29 30 public long getNumerator(){ 31 return numerator; 32 } 33 public long getDenominator(){ 34 return denominator; 35 } 36 37 public Rational add(Rational secondRational){ 38 long n=numerator*secondRational.getDenominator()+ 39 denominator*secondRational.getNumerator(); 40 long d=denominator*secondRational.getDenominator(); 41 return new Rational(n,d); 42 } 43 44 public Rational subtract(Rational secondRational){ 45 long n=numerator*secondRational.getDenominator()- 46 denominator*secondRational.getNumerator(); 47 long d=denominator*secondRational.getDenominator(); 48 return new Rational(n,d); 49 } 50 51 public Rational multiply(Rational sR){ 52 long n=numerator*sR.getNumerator(); 53 long d=denominator*sR.getDenominator(); 54 return new Rational(n,d); 55 } 56 57 public Rational divide(Rational sR){ 58 long n=numerator*sR.denominator; 59 long d=denominator*sR.numerator; 60 return new Rational(n,d); 61 } 62 63 public String toString(){ 64 if(denominator==1) 65 return numerator+""; 66 else 67 return numerator+"/"+denominator; 68 } 69 70 public boolean equals(Object parm1){ 71 if((this.subtract((Rational)(parm1))).getNumerator()==0) 72 return true; 73 else 74 return false; 75 } 76 77 78 79 @Override 80 public int compareTo(Object o) { 81 // TODO Auto-generated method stub 82 if((this.subtract((Rational)o)).getNumerator()>0) 83 return 1; 84 else if((this.subtract((Rational)o)).getNumerator()<0) 85 return -1; 86 else 87 return 0; 88 } 89 90 @Override 91 public int intValue() { 92 // TODO Auto-generated method stub 93 return (int)doubleValue(); 94 } 95 96 @Override 97 public long longValue() { 98 // TODO Auto-generated method stub 99 return (long)doubleValue(); 100 } 101 102 @Override 103 public float floatValue() { 104 // TODO Auto-generated method stub 105 return (float)doubleValue(); 106 } 107 108 @Override 109 public double doubleValue() { 110 // TODO Auto-generated method stub 111 return numerator*1.0/denominator; 112 } 113 114 115 116 117 }
有理数封装在Rational对象中。在机器内部,有理数总表示为它的最简形式,分子决定有理数的符号,分母总为正数。
gcd()方法是私有静态的。
Object类中的toString方法和equals方法在Rational类中被覆盖。toString()方法以numerator/denominator的形式返回一个Rational对象的字符串表示。
标签:
原文地址:http://www.cnblogs.com/xingzhui/p/5720875.html