java中怎么定义多项式?
代码示例
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner con=new Scanner(System.in);
//********************************实现输入************************************
int a=con.nextInt(); //输入幂次(第一个一定最大,最后一个一定最小。中间可以不按顺序)
int [] powers=new int[a+1]; //建立幂次数组
int b; //定义系数项
int max=a; //记录最高幂次
int count=0; //记录输入的多项式次数
while(a>=0&&a<=100)
{
if(a==0)
{
if(count==0)
{
count++;
}//当第一次输入的幂次是0,则 记录下来。count加1
else
{
b=con.nextInt();
powers[a]=powers[a]+b;
break;
}
}
b=con.nextInt();
powers[a]=powers[a]+b;
a=con.nextInt();
}
//*********************************实现输出************************************
for(int i=max;i>=0;i--)
{
//如果最高次幂是0,那么直接输出常数项然后跳出循环
if(max==0)
{
System.out.println(powers[a]);
break;
}
//0系数项不需要输出,直接下一次循环
else if(powers[i]==0)
{
continue;
}
else if(powers[i]>0)
{
if(powers[i]!=1)
{
if(i>1)
{
System.out.print(powers[i]+"x"+i);
}
else if(i==1)
{
System.out.print(powers[i]+"x");
}
else if(i==0)
{
System.out.print(powers[i]);
}
}
}
if(i!=0){System.out.print("+");}
}
}
Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有