如何使用bigintegers获取floatValue()equals()和compareTo()以实现以下功能

时间:2010-09-11 00:51:51

标签: java biginteger

public class BigFraction
{
 private BigInteger num;
 private BigInteger denom;
 //public static final BigFraction ZERO;
 /**
  *
  * Creates a BigFraction with numeriator BigInteger.ZERO and denominator BigInteger.ONE
  *
  */
 public BigFraction()
 {
   //should be 0/1
   num = BigInteger.ZERO;
   denom = BigInteger.ONE;
 }
 public BigFraction(BigInteger _num, BigInteger _denom)
 {
   num = _num;
   denom = _denom;
 }
 public BigFraction(BigInteger n)
 {
   //n/1
   num = n;
   denom = BigInteger.ONE;
 }
 public BigFraction(int _num, int _denom)
 {
  num = BigInteger.valueOf(_num);
  denom = BigInteger.valueOf(_denom);
 }
 public BigFraction add(BigFraction that)
 {
   return new BigFraction(num.multiply(that.denom).add(that.num.multiply(denom)), denom.multiply(that.denom));
 }
 public BigFraction multiply(BigFraction that)
 {
   return new BigFraction(num.multiply(that.num), denom.multiply(that.denom));
 }
 public BigFraction divide(BigFraction that)
 {
   return new BigFraction(num.multiply(that.denom), denom.multiply(that.num));
 }
 public BigFraction subtract(BigFraction that)
 {
   return new BigFraction(num.multiply(that.denom).subtract(that.num.multiply(denom)), denom.multiply(that.denom));
 }
 public BigFraction abs()
 {
   return new BigFraction(num.abs(), denom.abs());
 }
 public String toString()
 {
   return num + "/" + denom;
 }
 public int compareTo(BigFraction that)
 {
   return new BigFraction(num, denom).compareTo(new BigFraction(that.num, that.denom));
 }
 public boolean equals(Object o)
 {
   if(new BigFraction(num,denom) == o);
   return true;
 }
 public double floatValue()
 {
   //double num = num;
   //double denom = denom;
   return 0;
   //nasty!!!!!
 }
 public BigFraction negate()
 {
   return new BigFraction(BigInteger.ZERO.subtract(num),denom);
 }
 public BigFraction pow(int n)
 {
   return new BigFraction(num.pow(n), denom.pow(n));
 }
}

1 个答案:

答案 0 :(得分:1)

public boolean equals(Object o) {
    if(new BigFraction(num,denom) == o);
    return true;
}

“if”实际上并没有做任何事情。另外,只检查它是否是同一个对象将无法给出正确的结果。你能做的是:

return o.num.equals(num) && o.denom.equals(o.denom);

但是你需要确保课程自动减少2/4到1/2。

public double floatValue() {
    return num.floatValue() / denom.floatValue();
}

当然,这并不总是有效(特别是如果denom为0)。