【问题标题】:Java fraction calculator throws exception for division by zero when trying to simplifyJava分数计算器在尝试简化时抛出被零除的异常
【发布时间】:2015-02-02 17:40:49
【问题描述】:

我有以下类,我试图用它来执行分数之间的计算,但是我时不时地从简化函数中得到一个除以零的异常,我无法弄清楚它为什么这样做

public class Fraction {

    private int top;
    private int bottom;

    Fraction(int t, int b) {
        top = t;
        bottom = b;
        simplify();
    }

    public int getTop() {
        return top;
    }

    public int getBottom() {
        return bottom;
    }

    public void simplify() {
        if (bottom % top == 0) {
            bottom /= top;
            top /= top;
        } else {
            int divisor = gcd(bottom, top);
            top /= divisor;
            bottom /= divisor;
        }
    }

    public Fraction add(Fraction f) {
        if (bottom == f.getBottom()) {
            return new Fraction(top + f.getTop(), bottom);
        } else {
            return new Fraction(((top * f.getBottom()) + (f.getTop() * bottom)), bottom * f.getBottom());
        }
    }

    public Fraction subtract(Fraction f) {
        if (bottom == f.getBottom()) {
            return new Fraction(top - f.getTop(), bottom);
        } else {
            return new Fraction(((top * f.getBottom()) - (f.getTop() * bottom)), bottom * f.getBottom());
        }
    }

    public Fraction multiply(Fraction f) {
        return new Fraction(top * f.getTop(), bottom * f.getBottom());
    }

    private static int gcd(int a, int b) {
        if (a == 0 || b == 0) {
            return a + b;
        } else {
            return gcd(b, a % b);
        }
    }

    @Override
    public String toString() {
        return top + "/" + bottom;
    }
}

【问题讨论】:

    标签: exception fractions divide-by-zero


    【解决方案1】:

    top 为零时,语句bottom % top 产生除以零错误。

    您可以通过将simplify() 方法的第一行更改为:

    if (top != 0 && bottom % top == 0) {
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-16
      • 2021-09-13
      • 1970-01-01
      • 2016-08-05
      • 1970-01-01
      • 2016-11-30
      • 2014-04-20
      • 2021-02-19
      相关资源
      最近更新 更多