题描述:设计一个简单一元多项式计算器。基本要求:(1)输入并建立多项式; (2)输出多项式; (3)两个多项式相加,输出结果多项式: (4)两个多项式相减,输出结果多项式 可以根据输入变量的值,计算出多项式的结果,且算法的效率高。 思路
时间: 2024-02-16 13:03:25 浏览: 72
这个简单一元多项式计算器可以采用链表的数据结构进行存储和计算。每个节点包含两个属性:系数和指数。可以设计一个Polynomial类,其中包含以下成员函数:
1. addTerm(double coefficient, int exponent):添加一个新的项到多项式中,系数为coefficient,指数为exponent。
2. print():输出多项式。
3. add(Polynomial p):将两个多项式相加,返回结果多项式。
4. subtract(Polynomial p):将两个多项式相减,返回结果多项式。
在这个Polynomial类中,可以采用链表来存储多项式每一项的系数和指数,头结点表示多项式的开头。在addTerm()函数中,可以按照指数从大到小的顺序插入新的项,这样可以保证多项式始终是有序的。
在add()和subtract()函数中,可以采用类似于归并排序的思想,将两个多项式按照指数从大到小的顺序遍历,比较每一项的指数大小,然后生成一个新的多项式。具体实现可以参考下面的代码:
```python
class Node:
def __init__(self, coefficient, exponent):
self.coefficient = coefficient
self.exponent = exponent
self.next = None
class Polynomial:
def __init__(self):
self.head = Node(None, None)
def addTerm(self, coefficient, exponent):
current = self.head
while current.next != None and current.next.exponent > exponent:
current = current.next
if current.next != None and current.next.exponent == exponent:
current.next.coefficient += coefficient
else:
new_node = Node(coefficient, exponent)
new_node.next = current.next
current.next = new_node
def print(self):
current = self.head.next
while current != None:
if current.coefficient > 0:
print("+", end="")
print(current.coefficient, "x^", current.exponent, end="")
current = current.next
print("")
def add(self, p):
result = Polynomial()
current1 = self.head.next
current2 = p.head.next
while current1 != None and current2 != None:
if current1.exponent > current2.exponent:
result.addTerm(current1.coefficient, current1.exponent)
current1 = current1.next
elif current1.exponent < current2.exponent:
result.addTerm(current2.coefficient, current2.exponent)
current2 = current2.next
else:
result.addTerm(current1.coefficient + current2.coefficient, current1.exponent)
current1 = current1.next
current2 = current2.next
while current1 != None:
result.addTerm(current1.coefficient, current1.exponent)
current1 = current1.next
while current2 != None:
result.addTerm(current2.coefficient, current2.exponent)
current2 = current2.next
return result
def subtract(self, p):
result = Polynomial()
current1 = self.head.next
current2 = p.head.next
while current1 != None and current2 != None:
if current1.exponent > current2.exponent:
result.addTerm(current1.coefficient, current1.exponent)
current1 = current1.next
elif current1.exponent < current2.exponent:
result.addTerm(-current2.coefficient, current2.exponent)
current2 = current2.next
else:
result.addTerm(current1.coefficient - current2.coefficient, current1.exponent)
current1 = current1.next
current2 = current2.next
while current1 != None:
result.addTerm(current1.coefficient, current1.exponent)
current1 = current1.next
while current2 != None:
result.addTerm(-current2.coefficient, current2.exponent)
current2 = current2.next
return result
```
这样,我们就可以使用这个Polynomial类来输入、输出、相加、相减多项式了。
阅读全文