tips:对于100%数据,0 ≤n≤100,−100≤系数<=100
将符号、系数、指数分开输出
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int n;
int len=0;
scanf("%d",&n);
int a[105];
for(int i=n;i>=0;i--)
scanf("%d",&a[i]) ;
//由于有0次幂,因此特别构造这样的循环
for(int i=n;i>=0;i--)
{
int ax =a[i];
//正负号
if(ax==0) //系数为0,不输出
{
continue;
}
else if(ax>0)
{
if(i!=n) //n次项,位于开始,不需要+
printf("+");
}
else //负号跟随系数即可
{
;
}
//系数
if(i==0) //0次幂,都要输出
{
printf("%d",ax);
}
else
{
if(ax==1)
;
else if(ax==-1)
printf("-");
else
printf("%d",ax);
}
if(i>1) //如果不是0次幂,正常输出
printf("x^%d",i);
else if(i==1)
printf("x");
else
;
}
printf("\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int n=0;
scanf("%d",&n);
int a[n+1];//里面赋值为n不能初始化
int b=n+1;
int tmp=200;
for (int i = 0; i <= n; i++)
{
scanf("%d",&a[i]);
if (a[i]!=0&&tmp>i)
{
tmp=i;
//printf("%d\n",tmp);
}
}
for (int i = tmp; i <= n; i++)
{
if (i==tmp&&a[tmp]>0)
{
if (a[tmp]>1)
{
printf("%dx^%d",a[tmp],b-1);
}
else
{
printf("x^%d",b-1);
}
}
else if(i==tmp&&a[tmp]<0)
{
if (a[tmp]==-1)
{
printf("-x^%d",b-1);
}
else
{
printf("%dx^%d",a[tmp],b-1);
}
}
else if (tmp<i&&i<n-1)
{
if (a[i]==-1)
{
printf("-x^%d",b-i-1);
}
else if (a[i]==1)
{
printf("+x^%d",b-i-1);
}
else if (a[i]>1)
{
printf("+%dx^%d",a[i],b-i-1);
}
else if (a[i]==0)
{
;
}
else
{
printf("%dx^%d",a[i],b-i-1);
}
}
else if (i==n-1)
{
if (a[i]==-1)
{
printf("-x");
}
else if (a[i]==1)
{
printf("+x");
}
else if (a[i]>1)
{
printf("+%dx",a[i]);
}
else if (a[i]==0)
{
;
}
else
{
printf("%dx",a[i]);
}
}
else
{
if (a[i]>0)
{
printf("+%d",a[i]);
}
else if (a[i]==0)
{
;
}
else
{
printf("%d",a[i]);
}
}
}
return 0;
}
- 将多项式分为 系数+两部分
- 考虑正负号(包括第一个为正数时)
- 考虑x^1, x^0的特殊性(系数,格式)
- 考虑系数为1,-1,0时的特殊性