多项式处理

一元多项式相加

在这里插入图片描述

我给出的解法是:

在这里插入图片描述

一元多项式相乘

在这里插入图片描述

我给出的解法是

import java.util.Scanner;

class poly {
    int e;//指数
    double k;//系数
}

public class Main1 {
    //多项式相乘(和多项式相加原理相同)
    //0.定义要用的数组或者类)
    //1.读入第一个多项式(先读入多项式的项数,再利用for循环)
    //2.读入第二个多项式 (处理和第一个多项式的关系)
    //3.计数(非零项的个数)
    //4.输出非零项(for循环)(一般是从大到小)

    public static void main(String args[]) {

        double[] ans = new double[2001]; //存放结果
        int s1;//第一个多项式非零项的个数
        int s2;//第二个多项式非零项的个数
        poly[] p = new poly[1001];//对象数组(引用类型,我很容易在这里写成int性别的数组)
        int count = 0;

        Scanner in = new Scanner(System.in);
        s1 = in.nextInt();
        for (int i = 0; i < s1; i++) {
            p[i] = new poly();
            p[i].e = in.nextInt();
            p[i].k = in.nextDouble();
        }
        s2 = in.nextInt();
        for (int i = 0; i < s2; i++) {  //输入一项处理一项
            int exp;//指数
            double cof;//系数
            exp = in.nextInt();
            cof = in.nextDouble();
            for (int j = 0; j < s1; j++) {//与第一个多项式的每一项相乘
                //系数相乘,指数相加
                ans[exp + p[j].e] += p[j].k * cof;

            }
        }

        //累积求count
        for (int i = 0; i <= 2000; i++) {
            if (ans[i] != 0.0) {
                count ++;
            }
        }
        System.out.print(count);
        //输出
        for (int i = 2000; i >= 0; i--) {
            if(ans[i]!=0.0){
               // System.out.print(" "+i+" "+ans[i]);
                System.out.printf(" %d %.1f",i,ans[i]);
            }
        }


    }

}

猜你喜欢

转载自blog.csdn.net/qq_41033299/article/details/88807144
今日推荐