洛谷刷题 P1067 [NOIP2009 普及组] 多项式输出
题目传送:P1067 [NOIP2009 普及组] 多项式输出 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
思路
该题主要考察能否想到所有输入的情况,即对系数和次方为特殊值时进行讨论,如系数是±1,0时,次方是n和1时的系数情况,以及0次方,下面是所有特殊情况,以次方数为主元分类
- n次方,系数为正时不需要符号‘+’
- n-1次方到2次方,正数加符号‘+’,负数加符号‘-1’(负系数本身带符号,直接输出就行),并且显示次方数
- 1次方,不需要显示次方数
- 常数,不需要带x
- 系数为0,直接跳过
- 多项书最高项是常数,直接输出
AC代码
#include<iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int a[102];
for (int i = 0; i <= n; i++)
{
cin >> a[i]; // 读入系数
}
for (int i = 0; i <= n; i++)
{
if (n == 0) // 0次方
{
cout << a[i];
break;
}
if (a[i] == 0) continue; // 系数为0,跳过
if (i == 0) // n次方,如果为正不用加符号
{
if (a[i] == 1) cout << "x^" << n-i;
else if (a[i] == -1) cout << "-x^" << n-i;
else if (a[i] > 1) cout << a[i] << "x^" << n-i;
else cout << a[i] << "x^" << n-i;
}
else if (i==n-1) // 1次方,不用显示次方数
{
if (a[i] == 1) cout << "+x";
else if (a[i] == -1) cout << "-x";
else if (a[i] > 1) cout << "+" << a[i] << "x";
else cout << a[i] << "x";
}
else if (i == n) // 常数,考虑整数符号
{
if (a[i] > 0) cout << "+" << a[i];
else cout << a[i];
}
else // 正常
{
if (a[i] == 1) cout << "+x^" << n-i;
else if (a[i] == -1) cout << "-x^" << n-i;
else if (a[i] > 1) cout << "+" << a[i] << "x^" << n-i;
else cout << a[i] << "x^" << n-i;
}
}
}
原文地址:https://blog.csdn.net/Kenjuan/article/details/142719954
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!