我正在用Python编写二次公式。下面的函数应该解x^2-x-20。如果你算一下,你会得到-4和5
# Quadratic Formula
from math import sqrt
def findsolutions(a, b, c):
"""
Find solutions to quadratic equations.
"""
x1 = (-b + sqrt(b^2-4*a*c))/(2*a)
x2 = (-b - sqrt(b^2-4*a*c))/(2*a)
return x1, x2
x1, x2 = findsolutions(1,-1,-20)
print("The solutions to x^2-x-20 are", x1, "and", x2)
但是,如果您运行它,您会得到:
Traceback (most recent call last):
File "C:/Users/Atharv 2020/Desktop/Python/1. Quadratic Formula.py", line 11, in <module>
x1, x2 = findsolutions(1,-1,-20)
File "C:/Users/Atharv 2020/Desktop/Python/1. Quadratic Formula.py", line 7, in findsolutions
x1 = (-b + sqrt(b^2-4*a*c))/(2*a)
ValueError: math domain error
那么到底发生了什么
在Python中,
^
是一个称为XOR(异或)的按位运算符我想你把它误认为是计算功率。在python中,可以使用
**
计算功耗所以像这样修复代码
相关问题 更多 >
编程相关推荐