设计一个算法,创建两个一元多项式,输出一元多项式,实现两个一元多项式相加,输出相加后的一元多项式
时间: 2023-05-20 10:03:56 浏览: 109
好的,这是一个比较简单的算法,可以使用数组来存储多项式的系数,下面是完整的代码:
```python
def create_poly():
n = int(input("请输入多项式的最高次数:"))
poly = [0] * (n+1)
for i in range(n, -1, -1):
poly[i] = int(input("请输入x^{}的系数:".format(i)))
return poly
def print_poly(poly):
n = len(poly) - 1
for i in range(n, -1, -1):
if poly[i] != 0:
if i == n:
print(poly[i], end='')
else:
print(" + ", end='')
print(poly[i], end='')
print("x^{}".format(i), end='')
def add_poly(poly1, poly2):
n1 = len(poly1)
n2 = len(poly2)
if n1 > n2:
poly = poly1.copy()
for i in range(n2):
poly[i] += poly2[i]
else:
poly = poly2.copy()
for i in range(n1):
poly[i] += poly1[i]
return poly
print("请输入第一个多项式:")
poly1 = create_poly()
print("第一个多项式为:")
print_poly(poly1)
print("\n请输入第二个多项式:")
poly2 = create_poly()
print("第二个多项式为:")
print_poly(poly2)
print("\n两个多项式相加的结果为:")
poly = add_poly(poly1, poly2)
print_poly(poly)
```
如果你有任何问题,可以随时问我。
阅读全文