【PAT】甲级1002——C语言实现

1002 A+B for Polynomials (25)(25 分)

This time, you are supposed to find A+B where A and B are two polynomials.

Input

Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial: K N1 a~N1~ N2 a~N2~ ... NK a~NK~, where K is the number of nonzero terms in the polynomial, Ni and a~Ni~ (i=1, 2, ..., K) are the exponents and coefficients, respectively. It is given that 1 <= K <= 10,0 <= NK < ... < N2 < N1 <=1000.

Output

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

翻译:

1002 A + B多项式(25)25 

这一次,你应该找到A + B,其中A和B是两个多项式。

输入

每个输入文件都包含一个测试用例。每一行都占用2行,每行包含多项式的信息:K N1 a〜N1〜N2 a〜N2〜... NK a〜NK〜,其中K是多项式中非零项的个数,Ni和a〜Ni〜(i = 1,2,...,K)分别为指数和系数。给出1 <= K <= 10,0 <= NK <...

产量

对于每个测试用例,您应该在一行中输出A和B的总和,格式与输入相同。请注意,每行末尾必须没有额外的空间。请精确到小数点后1位。

实现关键:1.格式问题,末尾无空格。2.系数和为零的项不输出。

实现方式:用两个数组分别存储系数和指数,暴力加减。太过繁琐,引以为戒。

#include 
#include 
#define N 1000

int main()
{
    float line1[N], line2[N];
    int m = 0, n = 0;
    for (int i=0; (scanf("%f", &line1[i])) != EOF ; i++)
    {
        if(getchar() == '\n')
            break;
    }
    for (int i=0; (scanf("%f", &line2[i])) != EOF ; i++)
    {
       if(getchar() == '\n')
           break;
    }
    m = line1[0];
    n = line2[0];

    float a[N], b[N];
    for(int i=1; i<2*m+1;i++)
    {
        a[i] = line1[2*i-1];
        b[i] = line1[2*i];
    }
    for(int i=1; i<2*n+1;i++)
    {
        a[m+i] = line2[2*i-1];
        b[m+i] = line2[2*i];
    }
    for(int i=1; i

其他简单的方法:

#include 
#include
int main()
{
    float a[1001];
    int i,k;
    float temp;
    // 初始化数组
    for(i = 0; i <= 1000; i++){
        a[i] = 0.0f;
    }
    // 分别输入两个多项式
    scanf("%d", &k);
    while(k--){
        scanf("%d%f", &i, &temp);
        a[i] += temp;
    }
    scanf("%d", &k);
    while(k--){
        scanf("%d%f", &i, &temp);
        a[i] += temp;
    }
    // 判断当前多项式的项数
    k = 0;
    for(i = 0; i <= 1000; i++){
        if(a[i]!=0.0){
                k++;
        }
    }
    printf("%d", k);
    // 项数为0则只输出k,且不带空格
    if(k != 0)
        printf(" ");
    for(i=1000; i >= 0; i--){
        if(a[i]!=0.0){
            printf("%d ", i);
            printf("%0.1f", a[i]);
            k--;
            // 输出最后一项后不带空格
            if(k != 0)
                printf(" ");
        }
    }
    return 0;
}

你可能感兴趣的:(【PAT】甲级)