这段代码为什么不起作用?(CS50P问题集1 – 数学解释器)

huangapple go评论64阅读模式
英文:

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}")

huangapple
  • 本文由 发表于 2023年6月6日 01:06:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76408611.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定