概述
方程X ^ 2 + 2x + 3 = 0没有真正的解决方案。当您尝试取b * b-4 * a * c平方根时,会出现ValueError ,这是负数。 您应该以某种方式处理此错误情况。 例如,尝试/除外:
import math
def main():
print "This program finds the real solution to a quadratic"
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 "The solutions are: ", root1, root2
main()
或者您可以提前检测到判别为负:
import math
def main():
print "This program finds the real solution to a quadratic"
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 "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.
最后
以上就是虚心大炮为你收集整理的python中输入提示_python - 在python中显示输入提示 - 堆栈内存溢出的全部内容,希望文章能够帮你解决python中输入提示_python - 在python中显示输入提示 - 堆栈内存溢出所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复