1002 A+B for Polynomials (25分)
This time, you are supposed to find A+B where A and B are two polynomials.
Input Specification:
Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:
K N1 aN1 N2 aN2 ... NK aNK
where K is the number of nonzero terms in the polynomial, Ni and aNi (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10,0≤NK<⋯<N2<N1≤1000.
Output Specification:
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.
Sample Input:
2 1 2.4 0 3.2
2 2 1.5 1 0.5
Sample Output:
3 2 1.5 1 2.9 0 3.2
一、试题分析:
- 本题是对多项式(polynomial)的处理:两个多项式求和
- 题目最后指明输出格式的限制:保留一位小数(Please be accurate to 1 decimal place)
- 指数范围:[0,1000]
- 系数范围:非零(包括小数和负数)
二、解题思路:
1. 数组不要开小了:num[1001]即可
2. 下面的判断要考虑全面:num[]、coe数据类型均为double类型
3. 不需要开多个数组,一个数组就够了:下标代表指数exp,对应值代表系数coe
(1)第一行数据循环输入后,coe直接存储到num[exp]即可
(2)第二行数据循环输入后,有两种方案:
- 法一:只做num[exp]+=coe操作;另外循环计算相加的总项数count。
- 法二:循环中就处理count值:当原num[exp]==0,项数必定增加count+=1;当更新后num[exp]==0,项数必定减少count-=1。
//法一
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double num[1001]={0.0};
double coe;
int k1,k2,exp;
int count = 0;
cin>>k1;
for(int i=0; i<k1; i++){
cin>>exp>>coe;
num[exp]=coe;
}
cin>>k2;
for(int i=0; i<k2; i++){
cin>>exp>>coe;
num[exp]+=coe;
}
for(int i=0;i<1001;i++){ //另外计算count值
if(num[i]!=0){
count++;
}
}
cout<<count;
for(int i=1000; i>=0; i--){
if(num[i]!=0){
cout<<' '<<i<<' ';
printf("%.1lf",num[i]);
cout<<' '<<i<<' '<<setiosflags(ios::fixed)<<setprecision(1)<<num[i];
}
}
return 0;
}
//法二
#include <iostream>
using namespace std;
int main()
{
double num[1001]={0.0};
double coe;
int k1,k2,exp;
int count;
cin>>k1;
count=k1;
for(int i=0; i<k1; i++){
cin>>exp>>coe;
num[exp]=coe;
}
cin>>k2;
for(int i=0; i<k2; i++){ //第二次输入循环中就处理count值
cin>>exp>>coe;
if(num[exp]==0){ //原值=0,项数必定增加
count++;
num[exp]+=coe;
}else{
num[exp]+=coe;
if(num[exp]==0){ //更新后的值=0,项数必定减少
count--;
}
}
}
cout<<count;
for(int i=1000; i>=0; i--){
if(num[i]!=0){
cout<<' '<<i<<' ';
printf("%.1lf",num[i]);
}
}
return 0;
}
三、知识点:
输出控制:保留一位小数
- cout输出但引入格式化输出流
- ios::fixed操作符:定义在<iostream>中
- iostream& setiosflags(long flags):定义在<iomanip>中
- setiosflags(ios::fixed):意思是用小数点形式来显示数据,有效数字位数默认为为6位
- setprecision(n):修改显示有效数字的位数
2. print输出
- printf("%.1lf",num[i]):%.1lf表示double类型数据保留一位小数
四、经验总结:
- 根据题目要求,定义合适的数据类型并且保持数据类型一致
- 看清题目,注意输出数据的格式控制(比如保留几位小数)