数学和变量问题 - Python 3.3
我正在尝试创建一个简单的计算器,但我使用的开发环境总是告诉我,我在用字符串进行数学运算。我试着把所有的变量都设置成双精度浮点数(double),但还是没有成功。
"""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!")
2 个回答
0
试着在它上面加一个
int()
来让它变得更好
int(input))
希望这对你有帮助
3
input()
函数返回的是一个字符串,而不是数字。你需要把它转换成数字:
add1 = int(input())
或者
add1 = float(input())
这要根据你希望你的计算器支持什么功能来决定,否则你实际上是在用字符串进行数学运算。