【发布时间】:2019-02-23 22:29:27
【问题描述】:
我正在尝试解决一项编程任务,但遇到了一些麻烦。任务内容如下:
考虑计算二次方程解的常用公式: ax2 + bx + c = 0 由下式给出 x = sqrt(b± b^2−4ac/2a) 编写程序从命令行读取 a、b 和 c 的值。使用异常处理缺少的参数,并处理 b^2-4ac 的无效输入
我的程序如下:
from math import sqrt
import sys
try:
a = float(sys.argv[1])
b = float(sys.argv[2])
c = float(sys.argv[3])
bac = b**2 - 4*a*c
if bac < 0:
raise ValueError
except IndexError:
while True:
input("No arguments read from command line!")
a = float(input("a = ? "))
b = float(input("b = ? "))
c = float(input("c = ? "))
bac = b**2 - 4*a*c
if bac > 0:
break
if bac < 0:
while True:
print("Please choose values of a,b,c so\
that b^2 - 4ac > 0")
a = float(input("a = ? "))
b = float(input("b = ? "))
c = float(input("c = ? "))
bac = b**2 - 4*a*c
if bac > 0:
break
except ValueError:
while True:
input("Please choose values of a,b,c so that b^2 - 4ac > 0")
a = float(input("a = ? "))
b = float(input("b = ? "))
c = float(input("c = ? "))
if bac > 0:
break
for i in range(-1,2,2): # i=-1, next loop > i=1
x = (b + i*sqrt(bac)) / (2*a)
print("x = %.2f"%(x))
它似乎工作正常,但在下面的情况下它没有:
terminal >
python quadratic_roots_error2.py
No arguments read from command line!
a = ? 1
b = ? 1
c = ? 1
Please choose values of a,b,c so that b^2 - 4ac > 0
a = ? 5
b = ? 2
c = ? -3
No arguments read from command line!
a = ? 5
b = ? 2
c = ? -3
x = -0.60
x = 1.00
为什么程序会弹出消息“No arguments read from command line!”?我希望程序打印 b^2-4ac > 0 的每个解决方案,并且每当 b^2-4ac 0”像它一样被打印出来。
【问题讨论】:
-
为什么不放一个循环语句来检查输入变量的值的性质?
-
输入收集代码有点重复。请参阅here 了解获取有效输入的各种有效方法。
标签: python exception input valueerror