gpt4 book ai didi

Python 简单浮点除法 : not accurate

转载 作者:太空宇宙 更新时间:2023-11-03 13:31:03 25 4
gpt4 key购买 nike

所以我对编程还很陌生,但我只是在研究一个简单的计算器。当我启动程序并尝试除法部分(尝试将 5 除以 2)时,输出为 3.0 。这 2 个数字是 float ,所以我真的不明白为什么这不起作用。其次,乘法也会给出错误的答案。

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

顺便说一句,我使用 Python 3.6.1。

最佳答案

这和你想的不一样:

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

关于Python 简单浮点除法 : not accurate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47364011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com