我在macos上使用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()
现在空闲将永久显示:
This program finds the real solution to a quadratic
Please enter the coefficients (a, b, c):
当我输入3个数字(例如:1,2,3)时,IDLE什么也不做。当我点击进入空闲崩溃(没有崩溃报告)。在
我退出并重新启动,但IDLE现在永久显示上述内容,不会响应其他文件。在
math
模块不支持复数。如果将import math
替换为import cmath
,将{编辑:我刚读到“这个程序找到二次曲线的真正解”。考虑到你只想要真正的根,你应该像凯文所指出的那样,检查是否存在负面歧视。在
方程X^2+2x+3=0没有实际解。当你试图取
b * b-4 * a * c
的平方根时,你会得到一个ValueError
,它是负数。你应该设法处理这个错误案例。例如,try/except:或者您可以提前检测到判别式为负:
^{pr2}$结果:
我认为你的计划失败的原因是:
结果是-8。在
通常平方根内不能有负数。在
就像我上面的人说的,导入cmath应该行得通。在
http://mail.python.org/pipermail/tutor/2005-July/039461.html
^{pr2}$=2.82842712475j
相关问题 更多 >
编程相关推荐