我想提出的是猜一个数字,你被告知程序,如果数字是高或低的思维程序。我没有收到错误,但我似乎无法更新while循环变量“猜测”,但它仍然等于50的高低是由教科书给出的公式,所以我不能改变的。
我曾尝试移动while循环内的变量,但是,它仍然不会更新。
print('Hello.')
print('Pick a secret number between 0 and 100.')
low = 0
high = 101
guess = 50
while True:
print('Is your secret number',guess)
use = input('Enter yes/higher/lower:\n').lower()
if use == 'yes':
print('Great!')
break
elif use == 'higher':
low = guess
guess = (guess-low)//2+low
elif use == 'lower':
high = guess
guess = (high-guess)//2+guess
else:
print('I did not understand.')
IIUC,low
,high
和guess
需要为每个循环更新。您的新guess
应该是你的新low
和high
的平均值。
由于是,你的猜测是一样的。例如,如果用户与'higher'
响应,guess-low
是0
。除以2
仍然0
,然后通过添加low
,这是guess
。
你可能会想这样的:
low = guess
guess = (high + low) // 2
和
high = guess
guess = (high + low) // 2
这是奇怪的,因为有一些错误公式。
elif use == 'higher':
low = guess
guess = (guess-low)//2+low
elif use == 'lower':
high = guess
guess = (high-guess)//2+guess
在这部分,由于low == high == guess
,guess - low
的结果和high - guess
将始终为0除以由图2还给出了0。因此,这两条线变得相当于guess = guess
。
这是因为你重新分配到low
和high
,我相信你的意思是保持猜测范围的上限和下限。
也许你的意思是guess += (high - guess) // 2
和guess -= (guess - low) // 2
?
你的问题似乎是可变的价值再分配“(我不知道这个词我是法国人),有等于:
=
您必须使用
猜+ =值
要么
猜=猜测+猜测
要么
猜想;猜测 - 猜
要么
猜 - 猜=
那是因为你使用的逻辑是错误的。
眼下,正在发生的事情是,
low = guess
guess = (guess - low) // 2 + low
作为low = guess
上述声明等同于,
guess = (guess - guess) // 2 + low
# guess = 0 + low
# guess = low
同样,对于高,
high = guess
guess = (high - guess) //2 + guess
作为high = guess
上述声明等同于,
guess = (high - high) // 2 + guess
# guess = 0 + guess
# guess = guess
这就是为什么它总是停留在50
。
为它工作的实际逻辑如下,
elif use == 'higher':
low = guess
guess = (guess + high) // 2
elif use == 'lower':
high = guess
guess = (guess + low) // 2
更改段将。它的工作!
希望这可以帮助! :)