第四章(数组) 编程题 1

题目内容:

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

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

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

输入格式:

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

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

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

输出格式:

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

  1. 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

题目难点分析:

多项式加减法,主要有以下难点,是一开始没考虑到的:

1. 某个多项式系数为1时,不能写成1x5,而应该是x5;

2. 某个多项式幂为1时,不能写成5x1,而应该是5x;

3. 首项前面不能加“+”号,因此需要做一个判断首项的记录;

4. 多项式只有0时输出0;

5. x的0次幂如果系数为0,则应该不输出,但我没实现出来……

 

以下是答案:

1 2 import java.util.Scanner; 3 4 public class Main { 5 6 public static void main(String[] args) { 7 // TODO Auto-generated method stub 8 9 Scanner in = new Scanner(System.in); 10 11 12 int[] a = new int[10]; 13 int[] b = new int[10]; 14 boolean isfirst = true; 15 16 17 while (true) 18 { 19 int i = in.nextInt(); 20 int j = in.nextInt(); 21 a[i] = j; 22 if ( i == 0) 23 { 24 break; 25 } 26 } 27 28 while (true) 29 { 30 int i = in.nextInt(); 31 int j = in.nextInt(); 32 b[i] = j; 33 if ( i == 0) 34 { 35 break; 36 } 37 } 38 in.close(); 39 40 for (int i =0; i < a.length ; i++) 41 { 42 if ( a[i] != 0 || b[i] != 0) 43 { 44 a[i] = a[i] + b[i]; 45 } 46 } 47 for (int i = a.length-1 ; i > 0; i--) 48 { 49 if (a[i] > 0) 50 { 51 if ( isfirst) 52 { 53 isfirst = false; 54 } 55 else 56 { 57 System.out.print("+"); 58 } 59 if ( a[i] == 1) 60 { 61 if ( i ==1) 62 { 63 System.out.print("x"); 64 } 65 else 66 { 67 System.out.print("x" + i); 68 } 69 } 70 else 71 { 72 if ( i ==1) 73 { 74 System.out.print(a[i] + "x"); 75 } 76 else 77 { 78 System.out.print(a[i] + "x" + i ); 79 } 80 } 81 82 } 83 else if (a[i]<0) 84 { 85 if ( i == 1) 86 { 87 System.out.print(a[i] + "x"); 88 } 89 else 90 { 91 System.out.print(a[i] + "x" + i ); 92 } 93 } 94 } 95 if ( a[0] != 0 && isfirst==false) 96 { 97 System.out.print("+" + a[0]); 98 } 99 else 100 { 101 System.out.print(a[0]); 102 } 103 } 104 }
原文地址:https://www.cnblogs.com/zhong717/p/5077980.html