中国MOOC_零基础学Java语言_第5周 数组_1多项式加法

第5周编程题

返回
 

第5周编程题

依照学术诚信条款,我保证此作业是本人独立完成的。

温馨提示:

1.本次作业属于Online Judge题目,提交后由系统即时判分。

2.学生可以在作业截止时间之前不限次数提交答案,系统将取其中的最高分作为最终成绩。

1
多项式加法(5分)

题目内容:

一个多项式可以表达为x的各次幂与系数乘积的和,比如:

2x6+3x5+12x3+6x+20

现在,你的程序要读入两个多项式,然后输出这两个多项式的和,也就是把对应的幂上的系数相加然后输出。

程序要处理的幂最大为100。

输入格式:

总共要输入两个多项式,每个多项式的输入格式如下:

每行输入两个数字,第一个表示幂次,第二个表示该幂次的系数,所有的系数都是整数。第一行一定是最高幂,最后一行一定是0次幂。

注意第一行和最后一行之间不一定按照幂次降低顺序排列;如果某个幂次的系数为0,就不出现在输入数据中了;0次幂的系数为0时还是会出现在输入数据中。

输出格式:

从最高幂开始依次降到0幂,如:

2x6+3x5+12x3-6x+20

注意其中的x是小写字母x,而且所有的符号之间都没有空格,如果某个幂的系数为0则不需要有那项。

输入样例:

6 2

5 3

3 12

1 6

0 20

6 2

5 3

2 12

1 6

0 20

输出样例:

4x6+6x5+12x3+12x2+12x+40

时间限制:500ms内存限制:32000kb
 
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		int a[] = new int[101];
		int b[] = new int[101];
		int c[] = new int[101];
		Scanner sc = new Scanner(System.in);

		int m = 0;// 每行输入两个数字,第一个表示幂次
		int n = 0;// 第二个表示该幂次的系数
		int count = 0;// 统计输出的个数

		do {
			m = sc.nextInt();
			n = sc.nextInt();

			a[m] = n;
		} while (m != 0);// 输入a表

		do {
			m = sc.nextInt();
			n = sc.nextInt();

			b[m] = n;
		} while (m != 0);// 输入b表

		for (int i = 0; i < 101; i++) {// 统计c表
			c[i] = a[i] + b[i];
		}

		for (int i = 100; i > 1; i--) {// 100次幂到2次幂
			if (c[i] != 0)// 只统计c表系数不为0
			{
				if (count > 0) {
					if (c[i] > 0) {
						System.out.print("+");
					}
				}

				if (c[i] != 1 && c[i] != -1) {// 系数不为1且不为-1
					System.out.print(c[i] + "x" + i);
				} else if (c[i] == 1) {// 系数为1
					System.out.print("x" + i);
				} else {// 系数为-1
					System.out.print("-x" + i);
				}

				count++;
			}
		}

		if (c[1] != 0) {// 1次幂
			if (count > 0) {
				if (c[1] > 0) {
					System.out.print("+");
				}
			}

			if (c[1] != 1 && c[1] != -1) {// 系数不为1且不为-1
				System.out.print(c[1] + "x");
			} else if (c[1] == 1) {// 系数为1
				System.out.print("x");
			} else {// 系数为-1
				System.out.print("-x");
			}

			count++;
		}

		if (c[0] != 0) {// 0次幂
			if (count > 0) {
				if (c[0] > 0) {
					System.out.print("+");
				}
			}

			System.out.print(c[0]);
			count++;
		}

		if (count == 0) {
			System.out.print("0");
		}
	}
}
原文地址:https://www.cnblogs.com/denggelin/p/6756334.html