多项式加法 中国大学mooc翁恺《零基础学Java语言》第5周编程题 我为什么只能通过两个例子
package weqeeq;
import java.util.Scanner;
public class Practice1{
static int k,h,f;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] ans = new int[101];// 下标对应幂次,内容对应系数
int[][] ploy1 = new int[101][2];//第一轮输入,以0为截止
int[][] ploy2 = new int[101][2];//第二轮输入,以0为截止
int[] cunm1=new int[102];//存放所有幂次的类型
int[] cunm2=new int[102];//将所有幂次从大到小存放
int times;// 每项前的系数
int pow;// 幂次
int cnt_1 = 0;
while (true) {
pow = sc.nextInt();
times = sc.nextInt();
ploy1[cnt_1][0] = pow;
ploy1[cnt_1][1] = times;
cnt_1++;
if (pow == 0)
break;
}
int cnt_2 = 0;
while (true) {
pow = sc.nextInt();
times = sc.nextInt();
ploy2[cnt_2][0] = pow;
ploy2[cnt_2][1] = times;
cnt_2++;
if (pow == 0)
break;
}
for (int i = 0; i < cnt_1; i++) {
ans[ploy1[i][0]] += ploy1[i][1];
cunm1[i]=ploy1[i][0];
k=i;
}
for (int i = 0; i < cnt_2; i++) {
for(int j=0;j<cnt_1;j++)if(ploy1[i][0]!=ploy2[i][0]) {cunm1[k++]=ploy2[i][0];}
ans[ploy2[i][0]] += ploy2[i][1];
}
cunm2[0]=cunm1[0];
h=0;
f=1;
TT:
for(;h<k;h++) {
for(int j=h+1;j>0;j--) {
if(cunm2[j]==cunm1[h])continue TT;
}
cunm2[f]=cunm1[h];
f++;
}
for(int j=0;j<101;j++)
for(int i=1;i<=cunm2.length-2;i++) {
if(cunm2[i]<cunm2[i+1]) {
int temp=cunm2[i];
cunm2[i]=cunm2[i+1];
cunm2[i+1]=temp;
}
}
String resurt="";
for(int i=1;i<=cunm2.length-2;i++) {
if(ans[cunm2[i]]!=0)
if(cunm2[i]!=0) {
if(cunm2[i]!=1) {
if(ans[cunm2[i]]==1) {
String temp="x"+cunm2[i];
if(ans[cunm2[i+1]]<0);
else if(ans[cunm2[i+1]]>0) temp=temp+"+";
resurt=resurt+temp;}
else if(ans[cunm2[i]]==-1) {
String temp="-x"+cunm2[i];
if(ans[cunm2[i+1]]<0);
else if(ans[cunm2[i+1]]>0) temp=temp+"+";
resurt=resurt+temp;
}
else {
String temp=ans[cunm2[i]]+"x"+cunm2[i];
if(ans[cunm2[i+1]]<0);
else if(ans[cunm2[i+1]]>0) temp=temp+"+";
resurt=resurt+temp;
}
}
}
}
if(ans[1]!=0)if(ans[0]>=0)
System.out.println(resurt=resurt+ans[1]+"x+"+ans[0]);
else System.out.println(resurt=resurt+ans[1]+"x"+ans[0]);
else if(ans[0]==0 && resurt!="") System.out.println(resurt=resurt+"+"+ans[0]);
else System.out.println(resurt=resurt+ans[0]);
}
}