我正在尝试创建一个简单的计算器,但我正在使用的IDE一直告诉我我正在尝试使用字符串执行数学运算。我尝试将所有变量分配给双精度,但它没有奏效。
"""Calculator program"""
loop = 1 # 1 means loop; anything else means don't loop.
choice = 0 # This variable holds the user's choice in the menu
add1 = 0.0
add2 = 0.0
sub1 = 0.0
sub2 = 0.0
mul1 = 0.0
mul2 = 0.0
div1 = 0.0
div2 = 0.0
result = 0.0
while loop == 1:
# Print the options user has
print ("Welcome to calculator.py")
print ("your options are:")
print (" ")
print ("1) Addition")
print ("2) Subtraction")
print ("3) Multiplication")
print ("4) Division")
print ("5) Quit calculator.py")
print (" ")
#Perform the desired operation
choice = int(input("Choose your option: ").strip())
if choice == 1:
add1 = input()
add2 = input()
result = add1 + add2
print(add1, add2)
print (add1, "+", add2, "=", result)
elif choice == 2:
sub2 = input()
sub1 = input()
result = sub1 - sub2
print (sub1, "-", sub2, "=", result)
elif choice == 3:
mul1 = input("Multiply this: ")
mul2 = input("with this: ")
result = mul1 * mul2
print (mul1, "*", mul2, "=", result)
elif choice == 4:
div1 = input("Divide this: ")
div2 = input("by this: ")
result = div1 / div2
print (div1, "/", div2, "=", result)
elif choice == 5:
loop = 0
print ("Thank-you for using calculator.py!")
答案 0 :(得分:3)
input()
返回一个字符串,而不是一个数字。你必须转换它:
add1 = int(input())
或
add1 = float(input())
取决于您希望计算器支持的内容,否则您确实使用字符串执行数学运算。
答案 1 :(得分:0)
尝试坚持
int()
要制作
int(input))
希望这有帮助