题意:输入为两行,每一行代表一个多项式,第一个数字表示多项式有几项,后面每两个数字分别代表一项中的指数和系数。要求两个多项式相加的和。

分析:用一个double型数组模拟即可,需要注意的是如果系数为0,则对应项不输出,另外输出结果保留一位小数。

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstring>
 4 #include<cmath>
 5 #include<iomanip>
 6 using namespace std;
 7 double p[1001];
 8 int main()
 9 {
10     ios::sync_with_stdio(false);
11     cin.tie(0);
12     cout.tie(0);
13     int k1,k2;
14     while(cin>>k1)
15     {
16         memset(p,0,sizeof(p));
17         for(int i=0;i<k1;i++)
18         {
19             int zs;double xs;
20             cin>>zs>>xs;
21             p[zs]+=xs;
22         }
23         cin>>k2;
24         for(int i=0;i<k2;i++)
25         {
26             int zs;double xs;
27             cin>>zs>>xs;
28             p[zs]+=xs;
29         }
30         int sum=0;//记录多项式相加后还有多少存在的项
31         for(int i=0;i<=1000;i++)
32         {
33             if(p[i]!=0.0)
34             {
35                 sum++;
36             }
37         }
38         cout<<sum;
39         for(int i=1000;i>=0;i--)
40         {
41             if(p[i]!=0.0)
42             {
43                 cout<<" "<<i<<" "<<fixed<<setprecision(1)<<p[i];//printf("%0.1f", p[i]);一样,个人输出习惯而已
44             }
45         }
46         cout<<endl;
47     }
48     return 0;
49 }

 

posted on 2020-08-02 17:53  寻雾~  阅读(55)  评论(0编辑  收藏  举报