#### Guessing Game using Binary search

``````import random

def guess():
a = 0
b = 100
c = random.randint(1,100)
count = 1

user = int(input("Guess a number from 1 to 100: "))
comp = int(input(f"\nIs ur number {c}\nIf its high write 0 \nIf its low write 2\nIf it is then write 1: "))

while comp != 1:
count += 1

if comp == 0:
c = (a + c) // 2

elif comp == 2:
c = (c + b) // 2

comp = int(input(f"\nIs ur number {c} \nif its high press 0 \nif its low press 2\nif its ur number press 1: "))

print(f"\nYour number was {user} and it took {count} turn to find ur number.")

guess()
``````

``````assuiming our guess number is  = 55

our random number genrated = 22

user will press 2 cause it low resulting a number = (22 + 100) // 2
= 61
since 61 in higher than 55

# here lies the problem in the 2nd loop
user will press 1 cause its high resulting a number = (0 + 61) // 2
= 30
``````

(22 + 61) // 2 导致它给我们 41

then (41 + 61) // 2 导致它打印 51

then (51 + 61) // 2 导致它打印 56

then (56 + 51 ) // 2 导致它打印 53

then (53 + 56 ) // 2 导致它打印 54

then (54 + 56 ) // 2 导致它打印 55

55 这是我们的猜测数字

1 个回复

``````def guess():
a = 0
b = 100
c = random.randint(1,100)
count = 1

user = int(input("Guess a number from 1 to 100: "))
comp = int(input(f"\nIs ur number {c}\nIf its high write 0 \nIf its low write 2\nIf it is then write 1: "))

while comp != 1:
count += 1

if comp == 0:
b=c
c = (a + c) // 2

elif comp == 2:
a=c
c = (c + b) // 2
comp = int(input(f"\nIs ur number {c} \nif its high press 0 \nif its low press 2\nif its ur number press 1: "))

print(f"\nYour number was {user} and it took {count} turn to find ur number.")
``````
1 使用向量进行二分搜索

2 如何使用递归创建二分搜索

3 链表上的二分搜索（使用递归）

4 使用矩阵进行二分搜索

2020-07-08 07:16:34 0 17   c/ binary
5 实现二分搜索猜谜游戏[关闭]

6 二分搜索练习

2013-01-11 16:04:20 1 164   c/ openvms
7 我们可以使用地图进行搜索而不是二分搜索吗？

8 如何使用二分搜索在 Set 中找到类似的项目？

10 使用二分搜索实现平方根