0

我正在尝试编写一个小型 Java 类。我有一个名为 BigNumber 的对象。我编写了添加两个正数的方法,以及减去两个也是正数的其他方法。

现在我希望他们处理负数。所以我写了几个'if'语句,例如。

if (this.sign == 1 /* means '+' */) {
    if (sn1.sign == 1) {
        if (this.compare(sn1) == -1 /* means this < sn1 */ ) return sn1.add(this);
        else return this.add(sn1);
    }

等等

不幸的是,代码看起来很丑。就像一堆 if 和 else。有没有更好的方法来编写这种代码?

编辑 我不能只是这样做,this.add(sn1)因为有时我想将正数添加到负数或将负数添加到负数。但是 add 只能处理正数。所以我必须使用基本的数学,例如:而不是将负数添加到负数,而是添加this.abs()(数字的绝对值)sn1.abs()并返回带有相反符号的结果。德鲁:这条线来自方法 _add。我使用这种方法来决定如何处理它收到的数字。发送他们添加方法?或者将它们发送到 subract 方法但顺序不同(sn1.subtract(this))?等等..

if (this.sign == 1) {
    if (sn1.sign == 1) {
        if (this.compare(sn1) == -1) return sn1.add(this);
        else return this.add(sn1);
    }
    else if (wl1.sign == 0) return this;
    else {
        if (this.compare(sn1.abs()) == 1) return this.subtract(sn1.abs());
        else if (this.compare(sn1.abs()) == 0) return new BigNumber(0);
        else return sn1.abs().subtract(this).negate(); // return the number with opposite sign;
    }
} else if (this.sign == 0) return sn1;
else {
    if (wl1.sign == 1) {
        if (this.abs().compare(sn1) == -1) return sn1.subtract(this.abs());
        else if (this.abs().compare(sn1) == 0) return new BigNumber(0);
        else return this.abs().subtract(sn1).negate();
    } else if (sn1.sign == 0) return this;
    else return (this.abs().add(wl1.abs())).negate();
}

如您所见 - 这段代码看起来很糟糕..

4

4 回答 4

1

您可以考虑使用补码算法。这将大大简化加法和减法。无需担心符号位,只需将数字相加即可。

于 2010-01-22T00:33:10.093 回答
0

像这样的东西可能更有吸引力:

if (this.sign == 1 && sn1.sign == 1) {
    return (this.compare(sn1) < 0) ? sn1.add(this) : this.add(sn1);
}
于 2010-01-21T22:54:33.523 回答
0

我建议你多花些方法;)这个怎么样:

if (isPositive() && other.isPositive()) {
  if (this.isBiggerThen(other)) {
    return this.plus(other);
  } else {
    return other.plus(this);
  }
}

请注意,我将 sn1 重命名为 other 和要指示的add方法plus,该方法返回总和以增加可读性。add如果将某些内容添加到对象本身(例如在 BigInteger 类中),通常会使用它。

isPositive 和 isBiggerThen 的实现非常简单:

private boolean isPositive() {
  return sign == 1;
}

private boolean isBiggerThen(BigNumber other) {
  return this.compare(other) > 0;
}
于 2010-01-21T23:11:01.650 回答
0

有几件事让我感到困惑。不应该添加是可交换的。即它应该为a + b 提供与b + a 相同的结果。

在大多数情况下,您只需确定符号是否相同即可添加绝对值。

例如

if (sign == sn1.sign)
   return add(sn1);// add the absolute values and keep the sign. 1 + 1 == 2, -1 + -1 == -2
if (sign == 0) return sn1;
if (sn1.sign == 0) return this;
// you only need to know which value is larger for subtraction.
// keep the sign of the first argument and substract the absolute value.
return compare(sn1) > 0 ? substract(sn1) : sn1.substract(this);
于 2010-05-11T20:27:01.283 回答