This time, you are supposed to find A+B where A and B are two polynomials.
这一次,你应该找到A+B其中A和B是两个多项式。
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.
输入规格:
每个输入文件包含一个测试用例。每一种情况占2行,每一行包含一个多项式的信息:
K N1 aN1 N2 aN2 ... NK aNK
K是多项式N中非零项的个数,Ni 和 aNi (i=1,2,⋯,K)分别是指数和系数,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.
输出规范:
对于每个测试用例,您应该在一行中输出A和B的和,格式与输入相同。请注意,每一行的末尾必须没有多余的空间。请精确到小数点后一位。
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
这道题就是两个多项式的相加,我自己写的代码又臭又长,而且结果只是部分正确。。。
测试了几个都是对的,不知道哪里出了问题,先记下来以后再看
#include <iostream>
using namespace std;
int main()
{
int k1,k2;
int a=0;
int a1[10],a2[10],c[20];
double b1[10],b2[10],d[20];
cin>>k1;
for(int i=0;i<k1;i++)
{
cin>>a1[i]>>b1[i];
}
cin>>k2;
for(int i=0;i<k2;i++)
{
cin>>a2[i]>>b2[i];
}
int k=k1+k2;
int m=0,n=0;
for(int t=0; t<k; t++)
{
if(a1[m]>a2[n]&&m<k1&&n<k2)
{
c[t]=a1[m];
d[t]=b1[m];
m++;
}
else if(a1[m]==a2[n]&&m<k1&&n<k2)
{
c[t]=a1[m];
d[t]=b1[m]+b2[n];
k--;
m++;
n++;
}
else if(a1[m]<a2[n]&&m<k1&&n<k2)
{
c[t]=a2[n];
d[t]=b2[n];
n++;
}
else if(m>=k1&&n<k2)
{
c[t]=a2[n];
d[t]=b2[n];
n++;
}
else if(n>=k2&&m<k1)
{
c[t]=a1[m];
d[t]=b1[m];
m++;
}
}
cout<<k<<" ";
for(int p=0;p<k-1;p++)
{
cout<<c[p]<<" "<<d[p]<<" ";
}
cout<<c[k-1]<<" "<<d[k-1];
return 0;
}
看了别人的代码,感觉自己真是low爆了
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int num1, num2;
int exponent;//指数
double coefficient;//底数
double input[1001] = {0};
cin >> num1;
for (int i = 0; i < num1; ++i)
{
cin >> exponent >> coefficient;
input[exponent] += coefficient;
}
cin >> num2;
for (int i = 0; i < num2; ++i)
{
cin >> exponent >> coefficient;
input[exponent] += coefficient;
}
int k = 0;//非零个数
for (int i = 0; i < 1001; ++i)
if (input[i] != 0)
++k;
cout << k;
for (int i = 1000; i >= 0; --i)
if (input[i] != 0){
cout<<setiosflags(ios::fixed)<<setprecision(1);//控制输出格式
cout << " " << i << " " << input[i];
}
return 0;
}
用一个数组input来记录多项式,数组下标就是指数,输入时就让底数相加,输出时只要输出底数非零的数组值就行了。
1.使用setprecision(n)可控制输出流显示浮点数的数字个数。C++默认的流输出数值有效位是6。
2. setprecision(n)与setiosflags(ios::fixed)合用,可以控制小数点右边的数字个数。setiosflags(ios::fixed)是用定点方式表示实数。