我正在用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那么到底是怎么回事呢?
发布于 2021-08-05 11:24:35
在Python语言中,^是一个称为异或(异或)的位运算符
我想你把它误认为是计算能力了。在python中,您可以使用**计算功耗。
x ** y-x的y次幂
所以像这样修复你的代码
x1 = (-b + sqrt(b**2-(4*a*c)))/(2*a)
https://stackoverflow.com/questions/68665628
复制相似问题