题目描述:http://pat.zju.edu.cn/contests/pat-a-practise/1002
用Java写出现返回非零的错误,换成C++
#include <iostream>
#include<iomanip>
#include <math.h>
using namespace std;
int main(){
int aNum, bNum, tmpExp,count=0,i;
double tmpCoe;
double array[1005];
for(i = 0 ; i<1005; i++){
array[i] = 0.0;
}
cin>>aNum;
while(aNum--){
cin >> tmpExp;
cin >> tmpCoe;
array[tmpExp] = tmpCoe;
count++;
}
cin>> bNum;
while(bNum--){
cin>> tmpExp;
cin>> tmpCoe;
count++;
if(array[tmpExp] != 0.0){
array[tmpExp] = array[tmpExp] + tmpCoe;
if(fabs(array[tmpExp])< 0.0001){
count = count-2;
}else{
count--;
}
}else{
array[tmpExp] = tmpCoe;
}
}
if(count == 0){
cout<<0;
}else{
cout<<count<<" ";
}
for( i = 1004; i>=0; i--){
if(array[i] != 0.0){
count-- ;
cout<<i<<" ";
cout<<fixed<<setprecision(1);
cout<<array[i];
if(count != 0){
cout<<" ";
}else{
cout<<endl;
}
}
}
return 0;
}需要注意的问题:(1)系数相加为0时删掉 (2)相加项数为0时,输出0不输出0后的空格 (3)使用setprecision设置小数点精度
本文提供了一个针对PAT A 1002问题的C++解决方案,该方案首先读取两个多项式的系数和指数,并将它们合并成一个多项式。代码详细展示了如何处理输入数据,进行多项式合并,并输出最终结果。注意系数相加为0的情况,确保输出格式符合题目要求。
422

被折叠的 条评论
为什么被折叠?



