adt的java_java算法:基于应用ADT例子

本文展示了如何使用抽象数据类型(ADT)实现Java中的多项式运算,包括创建多项式接口、实现多项式类以及多项式的加法、乘法和评估方法。还提供了一个二项式多项式客户程序示例,演示了这些操作的实际应用。最后提到了Horner算法在多项式求值中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java算法:基于应用ADT例子

例1:多项式ADT接口

Java代码 icon_copy.gif

classPoly{

Poly(int,int)

doubleeval(double)

voidadd(Poly)

voidmult(Poly)

publicString toString()

}

class Poly{

Poly(int,int)

double eval(double)

void add(Poly)

void mult(Poly)

public String toString()

}

例2:多项式客户程序

Java代码 icon_copy.gif

publicclassBinomial{

publicstaticvoidmain(String args[]){

intN =100;

doublep =1.1;

Poly y =newPoly(1,0);

Poly t =newPoly(1,0);

t.add(newPoly(1,1));

for(inti =0; i 

y.mult(t);

System.out.println(y +" ");

}

System.out.println("value: "+ y.eval(p));

}

}

public class Binomial{

public static void main(String args[]){

int N = 100;

double p = 1.1;

Poly y = new Poly(1,0);

Poly t = new Poly(1,0);

t.add(new Poly(1,1));

for(int i = 0; i < N; i++){

y.mult(t);

System.out.println(y + " ");

}

System.out.println("value: " + y.eval(p));

}

}

例3:多项式ADT的数组实现

Java代码 icon_copy.gif

classPoly{

privateintn;

privateint[] a;

Poly(intc,intN){

a =newint[N+1];

n = N +1;

a[N] = c;

for(inti =0; i 

a[i] =0;

}

}

doubleeval(doubled){

doublet =0.0;

for(inti = n -1; i >=0; i--){

t = t * d + (double)a[i];

}

returnt;

}

voidadd(Poly p){

int[] t =newint[(p.n > n) ? p.n : n];

for(inti =0; i 

t[i] = p.a[i];

}

for(intj =0; j 

t[j] += a[j];

}

a = t;

n = t.length;

}

voidmult(Poly p){

int[] t =newint[p.n + n -1];

for(inti =0; i 

for(inti j =0; j 

t[i+j] += p.a[i] * a[j];

}

}

a = t;

n = t.length;

}

publicString toString(){

String s ="";

for(inti =0; i 

s += a[i] +" ";

}

returns;

}

}

class Poly{

private int n;

private int[] a;

Poly(int c,int N){

a = new int[N+1];

n = N + 1;

a[N] = c;

for(int i = 0; i < N; i++){

a[i] = 0;

}

}

double eval(double d){

double t = 0.0;

for(int i = n - 1; i >= 0; i--){

t = t * d + (double)a[i];

}

return t;

}

void add(Poly p){

int[] t = new int[(p.n > n) ? p.n : n];

for(int i = 0; i < p.n; i++){

t[i] = p.a[i];

}

for(int j = 0; j < n; j++){

t[j] += a[j];

}

a = t;

n = t.length;

}

void mult(Poly p){

int[] t = new int[p.n + n -1];

for(int i = 0; i < p.n; i++){

for(inti j = 0; j < n; j++){

t[i+j] += p.a[i] * a[j];

}

}

a = t;

n = t.length;

}

public String toString(){

String s = "";

for(int i = 0; i < n; i++){

s += a[i] + " ";

}

return s;

}

}

注意:Horner算法:a4x4 + a3x3 + a2x2 + a1x + a0 = (((a4x + a3)x + a2)x + a1)x + a0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值