用Java编写一元稀疏多项式计算器,要完整代码

这是一个 Java 类,用于表示一元稀疏多项式。它包含了一些私有字段和方法,以及一些公有方法,供用户调用。

``` import java.util.Map; import java.util.TreeMap;

public class SparsePolynomial { // 私有字段:一个 TreeMap,用于存储多项式的各项系数 private TreeMap<Integer, Double> coefficients;

// 构造函数:创建一个空的多项式 public SparsePolynomial() { coefficients = new TreeMap<>(); }

// 私有方法:设置多项式的系数 private void setCoefficient(int degree, double coefficient) { // 如果系数为 0,则从多项式中删除该项 if (coefficient == 0) { coefficients.remove(degree); } else { // 否则,设置该项的系数 coefficients.put(degree, coefficient); } }

// 公有方法:获取多项式的系数 public double getCoefficient(int degree) { // 如果多项式中包含该项,则返回该项的系数 if (coefficients.containsKey(degree)) { return coefficients.get(degree); } else { // 否则,返回 0 return 0; } }

// 公有方法:将多项式加上另一个多项式 public void add(SparsePolynomial other) { // 遍历另一个多项式的所有项 for (Map.Entry<Integer, Double> entry : other.coefficients.entrySet()) { // 获取该项的次数和系数 int degree = entry.getKey(); double coefficient = entry.getValue(); // 将该项加到当前多项式中 setCoefficient(degree, getCoefficient(degree) + coefficient); } }

// 公有方法:将多项式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值