PAT 1002 A+B for Polynomials (25分) c语言实现

6 篇文章 0 订阅

具体要求

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:

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​​ <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

具体思路

恩。。很简单的多项式加法了,推荐去做做pta上面,浙大数据结构那一道多项式加法和乘法,比这个难些,而且这个可以用简单顺讯结构体来完成,十分基础。

具体代码

#include<stdio.h>
#include<stdlib.h>
#define MAX 1001
typedef struct node/*结构体*/
{
    int zhi;
    float xi;
}list;
list QW[MAX],AS[MAX],ZONG[MAX];/*三个全局结构体数组,对应,两个输入,一个输出*/
int CHA1()/*第一个结构体赋值*/
{
    int i,k;
    i=0;
    scanf("%d",&k);
    while(k--)
    {
        scanf("%d %f",&QW[i].zhi,&QW[i].xi);
        i++;
    }
    return i;
}
int CHA2()/*第二个结构体赋值*/
{
    int i,k;
    i=0;
    scanf("%d",&k);
    while(k--)
    {
        scanf("%d %f",&AS[i].zhi,&AS[i].xi);
        i++;
    }
    return i;
}
int JIA(int len1,int len2)/*相加*/
{
    int i,j,v;/*记录数组的下标*/
    float sum;
    i=j=0;
    v=0;
    while((len1-i)&&(len2-j))/*两个都不为空*/
    {
        if( QW[i].zhi>AS[j].zhi)/*第一个的指数大于第二个*/
        {
            ZONG[v].zhi=QW[i].zhi;
            ZONG[v].xi=QW[i].xi;
            v++;
            i++;
        }
        else if(QW[i].zhi<AS[j].zhi)
        {
            ZONG[v].zhi=AS[j].zhi;
            ZONG[v].xi=AS[j].xi;
            v++;
            j++;
        }
        else
        {
            sum=QW[i].xi+AS[j].xi;
            if((int)(sum)!=0)/*相等切系数加起来不等于0*/
            {
                ZONG[v].zhi=QW[i].zhi;
                ZONG[v].xi=sum;
                v++;
            }
            i++;
            j++;
        }
    }
    for(;len1-i>0;i++)/*接下来对剩余的加入这个数组*/
    {
        ZONG[v].zhi=QW[i].zhi;
        ZONG[v].xi=QW[i].xi;
        v++;
    }
    for(;len2-j>0;j++)
    {
        ZONG[v].zhi=AS[j].zhi;
        ZONG[v].xi=AS[j].xi;
        v++;
    }

    return v;
}
int main()
{
    int len1,len2,len3;
    len1=CHA1();
    len2=CHA2();
    len3=JIA(len1,len2);
    printf("%d",len3);
    for(int i=0;i<len3;i++)
       printf(" %d %.1f",ZONG[i].zhi,ZONG[i].xi);/*注意输出格式*/
    return 0;

}

在这里插入图片描述思路这些真的推荐去看看,浙大的慕课,数据结构,超级棒的,代码很多不足,仅供参考,欢迎指正!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值