擅长:python、mysql、java
<p>方程X^2+2x+3=0没有实际解。当你试图取<code>b * b-4 * a * c</code>的平方根时,你会得到一个<code>ValueError</code>,它是负数。你应该设法处理这个错误案例。例如,try/except:</p>
<pre><code>import math
def main():
print "This program finds the real solution to a quadratic"
print
a, b, c = input("Please enter the coefficients (a, b, c): ")
try:
discRoot = math.sqrt(b * b-4 * a * c)
except ValueError:
print "there is no real solution."
return
root1 = (-b + discRoot) / (2 * a)
root2 = (-b - discRoot) / (2 * a)
print
print "The solutions are: ", root1, root2
main()
</code></pre>
<p>或者您可以提前检测到判别式为负:</p>
^{pr2}$
<p>结果:</p>
<pre><code>This program finds the real solution to a quadratic
Please enter the coefficients (a, b, c): 1,2,3
there is no real solution.
</code></pre>