燃油表通常以分数形式指示油箱中还有多少燃油。例如,1/4 表示水箱已满 25%,1/2 表示水箱已满 50%,3/4 表示水箱已满 75%。
在名为fuel.py的文件中,实现一个程序,提示用户输入分数,格式为X/Y,其中X和Y中的每一个都是整数,然后以四舍五入到最接近的整数的百分比形式输出:油箱里有很多燃油。但是,如果剩余量为 1% 或更少,则输出 E 来指示水箱基本上是空的。如果剩余 99% 或更多,则输出 F 来表示水箱基本已满。
但是,如果 X 或 Y 不是整数、X 大于 Y 或 Y 为 0,则再次提示用户。 (Y 不一定是 4。)一定要捕获任何异常,例如 ValueError 或 ZeroDivisionError
:) input of 3/4 yields output of 75%
:) input of 1/3 yields output of 33%
:) input of 2/3 yields output of 67%
:) input of 0/100 yields output of E
:) input of 1/100 yields output of E
:( input of 100/100 yields output of F
Did not find "F" in "Fraction: "
:( input of 99/100 yields output of F
Did not find "F" in "Fraction: "
:) input of 100/0 results in reprompt
:( input of 10/3 results in reprompt
expected program to reject input, but it did not
:) input of three/four results in reprompt
:) input of 1.5/4 results in reprompt
:) input of 3/5.5 results in reprompt
:( input of 5-10 results in reprompt
expected program to reject input, but it did not
我的代码
def main():
a,b=get_fuel()
percent=round(a/b*100)
if percent<=1:
print("E")
elif percent>98:
print("F")
else:
print(f"{percent}%")
def get_fuel():
try:
while True:
fuel=input("Fraction: ")
x,y=fuel.split("/")
if x.isdigit() and y.isdigit():
if x<=y:
if y!= "0":
x=int(x)
y=int(y)
return x,y
else:
pass
else:
pass
except(ValueError,ZeroDivisionError):
pass
main()
check50
提供的链接在浏览器中查看结果。 我运行你的代码来重现你的错误。我只得到了 3 个。(你帖子中的输出有 4 个错误。) 当您收到错误时,预期行为
位于第一行,观察到的行为(错误)位于第二行。这是您的输出的示例:
check50
这意味着当用户输入“99/100”时,check50 期望看到打印“F”。相反,用户会被重新提示“分数”。链接的 HTML 输出清楚地表明了这一点。看起来像这样:您的错误之一是这种比较:
:( input of 99/100 yields output of F <---expected
Did not find "F" in "Fraction: " <---observed
执行此操作。因此,您正在比较 x 和 y 的字符串值,其测试结果与整数不同。
试试这个代码:if x<=y:
基于此,您应该能够弄清楚需要做什么来纠正错误。祝你好运。