a785簡單多項式逐項格式化

CPE:Polynomial Showdown (UVa 392)

分離正負號、係數與次方,組合精確輸出。

前往題目練習 →回報教學錯誤每筆處理九項,時間與額外空間 O(1)。

解題思路

依次從 8 次到 0 次掃描九個係數,零係數直接略過。對每個非零項先輸出符號:第一項只有負號,後續項才使用兩側帶空格的加減號;項的大小一律使用係數絕對值,避免產生 + - 的形式。

非常數項若係數絕對值為 1,省略數字;次方為 1 時只寫 x,為 2 以上時才寫 x^p。常數項一定輸出數值。用已產生字串是否為空判斷第一項,最後仍為空代表零多項式。每九個係數一筆,讀至 EOF,每筆只輸出一行。

Step-by-step animation

示意:2x²−x+3

回報動畫錯誤
步驟 1 / 3

二次項

係數 2,第一個正項不加正號。

2
2
2x^2
次方
2
已輸出項數
1

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
    int a[9];
    while (cin >> a[0]) {
        for (int i = 1; i < 9; ++i)
            cin >> a[i];
        string out;
        for (int i = 0; i < 9; ++i) {
            int c = a[i], p = 8 - i;
            if (!c)
                continue;
            out += out.empty() ? (c < 0 ? "-" : "") : (c < 0 ? " - " : " + ");
            if (p == 0 || abs(c) != 1)
                out += to_string(abs(c));
            if (p)
                out += "x";
            if (p > 1)
                out += "^" + to_string(p);
        }
        cout << (out.empty() ? "0" : out) << '\n';
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多