我对Python还是很陌生,在遇到除法问题时遇到了一个奇怪的错误。整个程序较大,但是相关的部分是:
problemNumber = 0
gamesWon = 0
gamesLost = 0
gameNumber = 0
percentageWon = 0
answer = 0.00
while problemNumber < 10:
numberOne = random.randrange(0,10,1)
numberTwo = random.randrange(1,10,1)
print("Answer the following question: ", numberOne, program, numberTwo)
response = float(input())
if program == "+":
answer = numberOne + numberTwo
elif program == "-":
answer = numberOne - numberTwo
elif program == "x":
answer = numberOne * numberTwo
elif program == "/":
answer = float(format(answer, '.2f'))
answer = numberOne / numberTwo
elif program == "^":
answer = numberOne ^ numberTwo
if response == answer:
print(random.choice(congratulation_Message))
gamesWon = gamesWon + 1
problemNumber = problemNumber + 1
else:
print(random.choice(admonishment_Message),"The answer was ", format(answer, '.2f'))
gamesLost = gamesLost + 1
problemNumber = problemNumber + 1
大多数答案都能正确运行,但是当答案与答案相同时,四舍五入到2位的BUT除法问题又会返回为不正确:
Answer the following question: 3 / 2
1.5
Great job!
Answer the following question: 0 / 2
0
Great job!
Answer the following question: 8 / 7
1.14
Incorrecto, my friend. The answer was 1.14
Answer the following question: 5 / 7
.71
Wrongo. The answer was 0.71
Answer the following question: 1 / 9
0.11
AAAAH. Wrong. The answer was 0.11
我认为我的所有内容格式都正确,但是显然有些不正确。
有什么想法吗?
答案 0 :(得分:-1)
我认为您需要像以前那样将其格式化为2f:
answer = numberOne / numberTwo
因为可能是在比较
0.11和0.11111111