python中输入提示_python - 在python中显示输入提示 - 堆栈内存溢出

方程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"

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值