0

学习python,目前正在学习二分法解题。我正在编写代码,该代码应该接受用户从 0 到 100 的猜测,并尝试使用二分法找到该猜测。这是代码:

answer = raw_input('Please think of a number between 0 and 100')
#I've been using 80 as my test case 

low = 0
high = 100

guess = (low+high)/2

while guess != answer:

    if guess < answer:
        low = guess
    else:
        high = guess


    guess = (low+high)/2

我意识到,当我的猜测 < 答案为 false 时,else 块不会执行,所以我的高数永远不会改变。为什么会这样?我在这里忽略了什么吗?

4

1 回答 1

4

您需要将用户输入转换为整数(raw_input()返回一个字符串):

answer = int(raw_input(...))

比较失败,因为您稍后将整数与字符串进行比较(在 Python2 中有效,但在 Python3 中无效):

>>> 10 < "50"
True
>>> 75 < "50"
True
于 2015-09-11T23:24:42.777 回答