执行时:
def guess(a..b) do
IO.puts "In rn = #{a}..#{b}"
guess(a..b, IO.getn("Is it greater than #{div(a + b, 2)} ? : ", 1) |> String.upcase == "Y")
end
def guess(a..b, true) do
guess(div(a + b, 2)..b)
end
def guess(a..b, false) do
guess(a..div(a + b, 2))
end
结果:
iex(1)> Test.guess(1..10)
1 In rn = 1..10
2 Is it greater than 5 ? : y
3 In rn = 5..10
4 Is it greater than 7 ? :
5 In rn = 5..7
6 Is it greater than 6 ? : n
7 In rn = 5..6
8 Is it greater than 5 ? :
9 In rn = 5..5
10 Is it greater than 5 ? : y
11 In rn = 5..5
12 Is it greater than 5 ? :
13 In rn = 5..5
14 Is it greater than 5 ? :
iex 没有在第 4、8 和 12 行等待用户输入 - 在收到输入后,它似乎运行了两次循环。
为什么会这样?
解决了:
显然,以这种方式使用 IO.getn 会发生一些奇怪的事情——可能将“Y”读为一个字节,而将“输入”读为一个单独的字节。替换 IO.gets 并且没有字符数似乎可以解决问题。或者,隔离 getn 方法调用可能会阻止此问题发生。