A1002 A+B for Polynomials (25分)【C语言】
分别用三个数组存放多项式1, 多项式2和 最终结果。需要注意:
- 两个多项式相加之后,系数可能为0,此时不需要输出,因此需要判断
- 最终输出结果是按照指数递减的顺序,注意格式
晴神直接没有对多项式进行存储,而是直接用一个数组先存多项式1, 然后直接在此基础上加上多项式2, 即得最终结果多项式,用的空间更少,更简便。
题目描述:
This time, you are supposed to find A+B where A and B are two polynomials.
输入格式:
输出格式:
For each test case you should output the sum of A and B in one line, with the same format as the input. Notice that there must be NO extra space at the end of each line. Please be accurate to 1 decimal place.
输入样例:
2 1 2.4 0 3.2
2 2 1.5 1 0.5
输出样例:
3 2 1.5 1 2.9 0 3.2
实现代码:
#include <stdio.h>
#define MAXN 1001
int main()
{
int cnt=0, i, K1, K2, e;
double A1[MAXN]={0}, A2[MAXN]={0}, A3[MAXN]={0}, c;
scanf("%d", &K1);
while(K1){
scanf("%d %lf", &e, &c);
A1[e] = c;
K1--;
}
scanf("%d", &K2);
while(K2){
scanf("%d %lf", &e, &c);
A2[e] = c;
K2--;
}
for(i=0; i<MAXN; ++i){
if(A1[i]!=0 || A2[i]!=0){
A3[i] = A1[i] + A2[i];
}
if(A3[i]!=0) cnt++;
}
printf("%d", cnt);
for(i=MAXN-1; i>=0; --i){
if(A3[i]!=0){
printf(" %d %.1f", i, A3[i]);
cnt--;
}
if(cnt == 0) break;
}
return 0;
}