英文:
Why this code isn't working? (CS50P Problem set 1 - math interpreter)
问题
exp = input("表达式:").split(" ")
x, y, z = exp
n1 = float(x)
n2 = float(z)
if y == "+":
print(n1 + n2)
elif y == "-":
print(n1 - n2)
elif y == "*":
print(n1 * n2)
elif y == "/":
print(n1 / n2)
print(round(float(x), 1))
英文:
exp = input("Expression: ").split(" ")
x,y,z = exp
n1 = float(x)
n2 = float(z)
if y == "+":
print(n1+n2)
elif y == "-":
print(n1-n2)
elif y == "*":
print(n1*n2)
elif y == "/":
print(n1/n2)
print(round(exp, 1))
when I check the code by - check50 cs50/problems/2022/python/interpreter
I get this error:
:( input of "1 + 1" yields output of 2.0
expected "2.0", not "2.0\nTraceback..."
Also:
type list doesn't define __round__ method
答案1
得分: 2
你不能在 round 函数中使用列表
exp = input("表达式: ").split(" ")
x, y, z = exp
n1 = float(x)
n2 = float(z)
if y == "+":
result = n1 + n2
elif y == "-":
result = n1 - n2
elif y == "*":
result = n1 * n2
elif y == "/":
result = n1 / n2
print(result)
print(round(result))
英文:
you cannot use a list in a round function
exp = input("Expression: ").split(" ")
x,y,z = exp
n1 = float(x)
n2 = float(z)
if y == "+":
result = n1+n2
elif y == "-":
result = n1-n2
elif y == "*":
result = n1*n2
elif y == "/":
result = n1/n2
print(result)
print(round(result))
答案2
得分: 0
因为 exp
是一个列表,你尝试使用 round
函数,但列表不支持被“四舍五入”。
英文:
It doesn't work because exp
is a list and you are trying to use it with the round
function, but lists do not support to be "rounded".
答案3
得分: 0
calculator = input("表达式: ").split(" ")
x, y, z = calculator
a = float(x)
b = float(z)
if y == "+":
print(f"{a + b:.1f}")
elif y == "-":
print(f"{a - b:.1f}")
elif y == "*":
print(f"{a * b:.1f}")
else:
print(f"{a / b:.1f}")
英文:
calculator = input("Expresion: ").split(" ")
x, y, z = calculator
a = float(x)
b = float(z)
if y == "+":
print(f"{a + b:.1f}")
elif y == "-":
print(f"{a - b:.1f}")
elif y == "*":
print(f"{a * b:.1f}")
else :
print(f"{a / b:.1f}")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论