while ... do
line to have the loop keep running as long as variable
ans
≠ "y".
low=1
high=100
try = 1
ans = ""
while ans ~= "y" do
g=math.floor((low+high)/2)
print("try",try,":is your number",g)
print("y=yes, l=too low, h=too high")
ans=input()
if ans == "l" then
low = g
end
if ans == "h" then
high = g
end
try = try + 1
end
if try-1 <= 10 then
print("See! I did it in under 10 tries!")
end
You want the while loop to keep looping if the correct guess was not given, right? In this case,
this means the person has answered the question (in the 2 print
statements) with an answer other than "y" (with
"y" standing for "yes"). What condition would you put in the while loop to keep it looping if ans≠ "y"?
The code works as follows: we start our guess range to be between low
and high
which is between
1 and 100. We always guess a number that is midway between the numbers in low
and high
. As
the program begins, this will be 50, which is (100+1)/2 (the math.floor
function is used to drop
any decimal point).
The program works by reassiging either low
or high
to its last guess and deriving its next
guess from "guess=low+high2." For example, if its first guess of 50 is "too low," it'll
assign varible low
to 50 (high
is still 100). The next guess will be 50+1002=75, etc.