我在Mac OS上使用IDLE for Python。我在.py文件中写了以下内容:
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): ")
discRoot = math.sqrt(b * b-4 * a * c)
root1 = (-b + discRoot) / (2 * a)
root2 = (-b - discRoot) / (2 * a)
print
print "The solutions are: ", root1, root2
main()
IDLE现在永久显示:
该程序找到了二次方
的真正解请输入系数(a,b,c):
当我输入3个数字(例如:1,2,3)时,IDLE什么都不做。当我点击进入IDLE崩溃时(没有崩溃报告)。
我退出并重新启动,但IDLE现在永久显示上述内容并且不会响应其他文件。
答案 0 :(得分:2)
对于等式X ^ 2 + 2x + 3 = 0,没有真正的解决方案。当尝试取ValueError
的平方根时,您将获得b * b-4 * a * c
,这是负数。你应该以某种方式处理这个错误案例。例如,try / except:
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()
或者您可以提前发现判别式为负数:
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): ")
discriminant = b * b-4 * a * c
if discriminant < 0:
print "there is no real solution."
return
discRoot = math.sqrt(discriminant)
root1 = (-b + discRoot) / (2 * a)
root2 = (-b - discRoot) / (2 * a)
print
print "The solutions are: ", root1, root2
main()
结果:
This program finds the real solution to a quadratic
Please enter the coefficients (a, b, c): 1,2,3
there is no real solution.
答案 1 :(得分:1)
math
模块不支持复数。如果您将import math
替换为import cmath
,将math.sqrt
替换为cmath.sqrt
,则您的脚本应该像魅力一样。
答案 2 :(得分:1)
我认为您的计划失败的原因是:
a, b, c = 1, 2, 3
num = b * b - 4 * a * c
print num
它出现为-8。
您通常不能在平方根中使用负数。
就像我上面的人所说的那样,导入cmath应该有用。
http://mail.python.org/pipermail/tutor/2005-July/039461.html
import cmath
a, b, c = 1, 2, 3
num = cmath.sqrt(b * b - 4 * a * c)
print num
= 2.82842712475j