0

我正在尝试创建一个简单的计算器,但我正在使用的 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!")
4

2 回答 2

3

input()返回一个字符串,而不是一个数字。您必须将其转换为:

add1 = int(input())

或者

add1 = float(input())

取决于您希望您的计算器支持什么,否则您确实是在使用字符串执行数学运算。

于 2013-02-28T16:08:55.273 回答
0

试着贴一个

    int()

在它上面做

    int(input))

希望这可以帮助

于 2013-02-28T16:48:56.683 回答