<p>在python x^2中,可以是x**2,x*x或pow(x,2)。
其他人给了你很好的建议,我想补充几点。
二次方程:ax^2+bx+c=0(调整使方程等于零!)
具有多项式项ax^2,bx,c;其系数为a,b,c为常数项。
然后二次公式:(-b+sqrt(b^2-4*a*c))/2a;解x</p>
<p>以上所有内容都正确地出现在您的代码中
但是,如果解停留在复数集合{C}中,您将遇到麻烦。你知道吗</p>
<p>这可以很容易地通过测量“判别式”来解决。你知道吗</p>
<p>判别式是b^2-4ac,并且</p>
<ul>
<li>如果判别式=0,则只有一个解</li>
<li>如果判别式大于0,则有两个实解</li>
<li>如果判别式<;0,则有两个复解</li>
</ul>
<p>考虑到上述条件,代码应该是这样的:</p>
<pre><code>import math
print ("Quadratic Equation Calculator")
a = float(input("Enter the coefficient of term `x ^ 2` (degree 2), [a]: "))
b = float(input("Enter the coefficient of term `x` (degree 1), [b]: "))
c = float(input("Enter the constant term (degree 0), [c]: "))
discriminant = pow(b, 2) - 4.0 * a * c
if discriminant == 0:
root1 = root2 = (-1 * b) / (2 * a)
elif discriminant < 0:
root1 = ((-1 * b) - math.sqrt(-discriminant) * 1j) / (2 * a)
root2 = ((-1 * b) + math.sqrt(-discriminant) * 1j) / (2 * a)
else:
root1 = ((-1 * b) - math.sqrt(discriminant)) / (2 * a)
root2 = ((-1 * b) + math.sqrt(discriminant)) / (2 * a)
print (root1)
print (root2)
</code></pre>
<p>类似的答案:<a href="https://stackoverflow.com/a/49837323/8247412">https://stackoverflow.com/a/49837323/8247412</a></p>
<p>下面我修改了pythonic编程的代码,因为numpy可以很好地找到多项式(二次和高阶)方程的根。
<a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.roots.html" rel="nofollow noreferrer">numpy.roots</a></p>
<pre><code>import numpy as np
print ("Quadratic Equation Calculator")
a = float(input("Enter the coefficient of term `x ^ 2` (degree 2), [a]: "))
b = float(input("Enter the coefficient of term `x` (degree 1), [b]: "))
c = float(input("Enter the constant term (degree 0), [c]: "))
coeffs = [a, b, c] # or d, e and so on..
roots = np.roots(coeffs)
print (roots)
</code></pre>