开发者

how to get the signs in the Polynomial in toString method?

i want to add the polynomials with the coeff getA(),getB() and getC() with the +ve or -ve signs. and remove the terms with zero coff like 2x^2+5 not 2x^2+0x+5 in general like (+/-)ax^2(+/-)bx(+/-)c.

public String toString() {

    if (getA().equals(DEFAULT_A)
        && getB().equals(DEFAULT_B)
        && getC().equals(DEFAULT_C)) {
        return "0";
    } else {
        String poly = "";
        if (!getA().equals(DEFAULT_A))开发者_C百科 {
            poly = getA().toString() + "x^2";
        }
        if (!getB().equals(MyDouble.zero)) {
            if (getB().compareTo(MyDouble.zero)) {
                return getB();
            }
        }
        poly += getB().toString() + "x";
        if (!getC().equals(MyDouble.zero)) {
            poly += getC().toString;
        }

        return poly;
    }
}


This would be alot simpler with plain doubles, This may give you an idea of what you can do.

public static String poly(double a, double b, double c) {
    return (a == 0 ? "" : toNum(a) + "x^2 ") +
            (b > 0 ? "+" : "") +
            (b == 0 ? "" : toNum(b) + "x ") +
            (c > 0 ? "+" : "") +
            (c == 0 ? "" : c == 1 ? "1" : c == -1 ? "-1" : toNum(c));
}

private static String toNum(double v) {
    return v == 1 ? "" : v == -1 ? "-" : 
           v == (long) v ? Long.toString((long) v) : Double.toString(v);
}

public static void main(String... args) {
    System.out.println(poly(1, 1.5, 2.5));
    System.out.println(poly(-1, -1, -1));
    System.out.println(poly(2, 0, 0));
    System.out.println(poly(0, -3, 0));
    System.out.println(poly(0, 0, -9));
}

prints

x^2 +1.5x +2.5
-x^2 -x -1
2x^2 
-3x 
-9
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜