我正在做一个项目,用户输入一个数字和一个列表,列表中任何与该数字最接近的项目都会打印出来。我遇到了一个问题,那就是while循环中if()语句中的行每次都在运行吗?我有一种感觉,这与python3中的if()语句缩进有关,但我不确定。有人知道为什么会这样吗?
import math
MatchingI = math.inf
while i < len(compareList):
if (abs(int(mainNum) - int(compareList[i])) < MatchingI):
MatchingI = int(compareList[i])
i += 1发布于 2021-04-26 09:43:19
我认为您需要将abs(int(mainNum) - int(compareList[i]))赋值给MatchingI,而不是将int(compareList[i])赋值给MatchingI。
import math
MatchingI = math.inf
while i < len(compareList):
if (abs(int(mainNum) - int(compareList[i])) < MatchingI):
MatchingI = abs(int(mainNum) - int(compareList[i]))
answer = compareList[i]
i += 1
print(answer)这不就是你要找的吗?
https://stackoverflow.com/questions/67259839
复制相似问题