A4.多项式输出 注释版题解
2025-04-16 21:07:11
发布于:辽宁
0阅读
0回复
0点赞
#include <bits/stdc++.h>
using namespace std;
int n;
int a[110];
int main() {
cin >> n;
for (int i = 0; i <= n; i++) {
cin >> a[i];
}
bool is_first = true; // 标记是否是第一个输出的项
for (int i = 0; i <= n; i++) {
int coeff = a[i];
if (coeff == 0) continue; // 跳过零系数项
int exp = n - i; // 当前项的次数
/* 处理符号 */
if (is_first) { // 第一个非零项特殊处理
if (coeff < 0) cout << '-';
is_first = false;
} else { // 后续项正常处理符号
cout << (coeff > 0 ? '+' : '-');
}
/* 处理系数绝对值 */
int abs_coeff = abs(coeff);
if (exp == 0) { // 常数项直接输出
cout << abs_coeff;
continue;
}
if (abs_coeff != 1) { // 系数不为1时需要显示
cout << abs_coeff;
}
/* 处理x部分 */
cout << 'x';
if (exp > 1) { // 次数大于1时显示指数
cout << '^' << exp;
}
}
/* 处理全零情况 */
if (is_first) cout << 0;
return 0;
}
这里空空如也
有帮助,赞一个