二分搜索是否可以猜测用户猜到了最高值?

Can a bisection search guess that the user guessed the highest value?

我正在尝试让计算机使用二分搜索来猜测我输入的 0 到 100 之间的数字。现在,对于我输入的所有数字,计算机可以在 7 次尝试内猜出,除了 100,其中它进入无限循环。我知道为什么会这样,因为我有 int(high+low)/2 所以程序最接近 100 的是 99.5(high=100, low=99),它会四舍五入到 99。所以程序会继续猜测 99。我如何修改我的代码以便它处理这个问题,而不必使用 if 语句专门猜测数字 100?

print("This is a bisection search, which I hopefully am going to beat. HAHAHA!")
for i in range(99999**9):
    high=100
    low=0
    number_of_searches=1
    print('enter a guess between 0 and 100')
    user_input =  int(input())
    
    guess = int((high+low)/2)
    while user_input != guess:
        if guess>user_input:
            high=guess
        else:
            low=guess 
        number_of_searches+=1
        guess=int((high+low)/2)
        
    print (" your number was found in ",number_of_searches, "search

es")

您可以将高设置为 101,它会找到它。

print("This is a bisection search, which I hopefully am going to beat. HAHAHA!")
for i in range(99999**9):
    high=101
    low=0
    number_of_searches=1
    print('enter a guess between 0 and 100')
    user_input =  int(input())

    guess = int((high+low)/2)
    while user_input != guess:
        if guess>user_input:
            high=guess
        else:
            low=guess 
        number_of_searches+=1
        guess=int((high+low)/2)

    print (" your number was found in ",number_of_searches, "searches")

如果您尝试查找 101,这将进入无限循环。所以只需将最大值设置为比您希望能够搜索的实际最大值大 1。