A1002 A+B for Polynomials (多项式A+B)

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 N​1​​ a​N​1​​​​ N​2​​ a​N​2​​​​ ... N​K​​ a​N​K​​​​

where K is the number of nonzero terms in the polynomial, N​i​​ and a​N​i​​​​ (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10,0≤N​K​​<⋯<N​2​​<N​1​​≤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

大致题意如下:

   给出两行,每行表示一个多项式,每行第一个数为此行多项式的项数,后面每两个数表示一项,分别表示这两个数的幂次和系数。求这两个多项式的和,以相同格式输出。

  如上样例所示,第一行多项式为F1(x) = 2.4x + 3.2 ;第二行多项式为 F2(x) = 1.5x^2 + 0.5x ;两式相加结果为 F(x) = 1.5x^2 + 2.9x + 3.2,按照格式输出即可。

#include <cstdio>
const int max_n = 1001;
double p[max_n] = {0};

int main(){
  int k,n,count = 0;
  double a;
  scanf("%d", &k);
  for(int i = 0; i < k; i++){
    scanf("%d %lf", &n, &a);
    p[n] += a;
  }
  scanf("%d", &k);
  for(int i = 0; i < k; i++){
    scanf("%d %lf", &n, &a);
    p[n] += a;
  }
  for(int i = 0; i < max_n; i++){
    if(p[i] !=  0)
      count++;
  }
  printf("%d", count);
  for(int i = max_n - 1; i >= 0; i--)
    if(p[i] != 0)
      printf(" %d %.1f", i ,p[i]);
  return 0;
}

注意:

  1. scanf时,double就应该用%lf,float就用%f
  2. printf无论是%f还是%lf没有区别,因为当printf函数当遇到float类型时会自动转化为double,从c语言标准来说printf并没有%lf的定义,虽然大多数编译器都能接受,但在做题时printf最好用%f,否则可能出现一些莫名其妙的错误;
  3. %.1f 表示四舍五入,保留一位小数
  4. %.2lf 值保留2位小数。

猜你喜欢

转载自blog.csdn.net/weixin_35093872/article/details/86296727