多项式加法——MOOC《零基础学Java语言》
作者:互联网
多项式加法——MOOC《零基础学习Java语言》
#第五周编程题
多项式加法
注意:
1.多项式全为0,显示0。
2.最高幂次前面不显示加减符号。
3.幂次为1,不显示.
4.系数为1或-1,不显示。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int[] Polynomials = new int[101];
int maxP=0;
int sum=0;
while( true ) {
int n=in.nextInt();
int k=in.nextInt();
Polynomials[n] = k;
sum += k;
if(n == 0) {
break;
}
}
while( true ) {
int n=in.nextInt();
int k=in.nextInt();
Polynomials[n] +=k;
sum += k;
if(n == 0) {
break;
}
}
if(sum == 0) {
System.out.print(sum);
}
for(int i=Polynomials.length-1;i>=0;i--) {
if(Polynomials[i] != 0 && i != 1) {
if(Polynomials[i] == 1 || Polynomials[i] == -1) {
System.out.print("x"+i);
}
else {
System.out.print(Polynomials[i]+"x"+i);
}
maxP = i;
break;
}
}
for(int i=maxP-1;i>=0;i--) {
if(Polynomials[i] != 0 && i > 1) {
if(Polynomials[i] == 1 || Polynomials[i] ==-1) {
if(Polynomials[i] > 0) {
System.out.print("+");
}
else {
System.out.print("-");
}
int v;
if(Polynomials[i] < 0) {
v = Polynomials[i] * (-1);
}
else {
v = Polynomials[i] ;
}
System.out.print("x"+i);
}
else {
if(Polynomials[i] > 0) {
System.out.print("+");
}
else {
System.out.print("-");
}
int v;
if(Polynomials[i] < 0) {
v = Polynomials[i] * (-1);
}
else {
v = Polynomials[i] ;
}
System.out.print(v+"x"+i);
}
}
else if(Polynomials[i] != 0 && i == 1) {
if(Polynomials[i] == 1 || Polynomials[i] ==-1) {
if(Polynomials[i] > 0) {
System.out.print("+");
}
else {
System.out.print("-");
}
int v;
if(Polynomials[i] < 0) {
v = Polynomials[i] * (-1);
}
else {
v = Polynomials[i] ;
}
System.out.print("x");
}
else {
if(Polynomials[i] > 0) {
System.out.print("+");
}
else {
System.out.print("-");
}
int v;
if(Polynomials[i] < 0) {
v = Polynomials[i] * (-1);
}
else {
v = Polynomials[i] ;
}
System.out.print(v+"x");
}
}
else if(Polynomials[i] != 0 && i == 0 ) {
if(Polynomials[i] > 0) {
System.out.print("+");
}
else {
System.out.print("-");
}
int v;
if(Polynomials[i] < 0) {
v = Polynomials[i] * (-1);
}
else {
v = Polynomials[i] ;
}
System.out.print(v);
}
}
}
}
标签:MOOC,Java,int,多项式,System,Polynomials,else,print,out 来源: https://blog.csdn.net/weixin_43347550/article/details/104905212