Python简单浮点除法:不准确

2024-04-25 23:56:31 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我对编程非常陌生,但我只是在做一个简单的计算器。 当我启动程序并尝试除法部分(尝试将5除以2)时,输出是3.0。这两个数字是浮点数,所以我真的不明白为什么这不起作用。第二,乘法也给出了错误的答案。你知道吗

from math import *

while True:

print("Options:")
print("Enter 'add' to add two numbers")
print("Enter 'subtract' or '-' to subtract two numbers")
print("Enter 'multiply' to multiply two numbers")
print("Enter 'divide' to divide two numbers")
print("Enter 'quit' to end the program")
user_input = input(": ")

if user_input == "quit":
    print ("Calculator stopped.")
    break
elif user_input == "subtract" or "-":
    num1 = float(input("num1: "))
    num2 = float(input("num1: "))
    print(num1 - num2)
elif user_input == "multiply" or "*":
    num1 = float(input("num1: "))
    num2 = float(input("num1: "))
    print(">> ", num1 * num2," <<")
elif user_input == "divide" or "/":
    num1 = float(input("num1: "))
    num2 = float(input("num1: "))
    sum = num1 / num2
    print(str(float(num1)/num2))
else:
    print("Unknown command")

顺便说一句,我使用python3.6.1。你知道吗


Tags: ortoinputfloatmultiplyprintsubtractenter
1条回答
网友
1楼 · 发布于 2024-04-25 23:56:31

这并不是你想的那样:

elif user_input == "subtract" or "-":

它的工作原理就好像它被分组如下:

elif (user_input == "subtract") or "-":

不管user_input的值是多少,这个条件都将求值为True(因为"-"是非空的,因此为True),并且将执行减法。你知道吗

(tried to divide 5 by 2), the output was 3.0

那是因为5减2等于3。代码是减法。你知道吗

你想要的东西更像:

from math import *

while True:

    print("Options:")
    print("Enter 'subtract' or '-' to subtract two numbers")
    print("Enter 'multiply' to multiply two numbers")
    print("Enter 'divide' to divide two numbers")
    print("Enter 'quit' to end the program")
    user_input = input(": ")

    if user_input == "quit":
        print ("Calculator stopped.")
        break
    elif user_input in ( "subtract", "-"):
        num1 = float(input("num1: "))
        num2 = float(input("num1: "))
        print(num1 - num2)
    elif user_input in ("multiply", "*"):
        num1 = float(input("num1: "))
        num2 = float(input("num1: "))
        print(">> ", num1 * num2," <<")
    elif user_input in ("divide", "/"):
        num1 = float(input("num1: "))
        num2 = float(input("num1: "))
        print(num1/num2)
    else:
        print("Unknown command")

相关问题 更多 >