多项式输出
2026-07-14 21:23:49
发布于:吉林
7阅读
0回复
0点赞
1.输入最高次数 max_degree,数组 coeff[d] 保存次数为 d 的项的系数;
2.从最高次遍历到 0 次,跳过系数为 0 的项;
3.符号规则:
第一项正数不输出加号,负数输出减号;
后面的项正数输出+,负数输出-;
4.常数项(d=0):直接输出系数绝对值;
5.次数 > 0 的项:
系数绝对值不等于 1 时,打印数字;
固定打印x;
次数大于 1 额外打印^次数,次数为 1 只打 x。
代码如下:
#include <iostream>
#include <cmath>
using namespace std;
int max_degree, coeff[105], num, abs_num;
bool first_item = true;
int main(){
cin >> max_degree;
for (int d = max_degree; d >= 0; d--){
cin >> coeff[d];
}
for (int d = max_degree; d >= 0; d--){
num = coeff[d];
if (num == 0)
continue;
if (first_item){
if (num < 0)
cout << "-";
first_item = false;
}
else{
if (num > 0)
cout << "+";
else
cout << "-";
}
abs_num = abs(num);
if (d == 0){
cout << abs_num;
}
else{
if (abs_num != 1)
cout << abs_num;
cout << "x";
if (d > 1){
cout << "^" << d;
}
}
}
return 0;
}
这里空空如也






有帮助,赞一个