如何在toString方法中获取Polynomial中的符号?

时间:2011-04-03 18:10:17

标签: java polynomial-math

我想用带有+ ve或-ve符号的coeff getA(),getB()和getC()添加多项式。并且删除条件为零coff,如2x ^ 2 + 5,而不是2x ^ 2 + 0x + 5一般像(+/-)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)) {
            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;
    }
}

1 个答案:

答案 0 :(得分:2)

这对于普通双打来说会更简单,这可能会让你知道你能做些什么。

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));
}

打印

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