gpt4 book ai didi

lua - io.read() 不工作

转载 作者:行者123 更新时间:2023-12-04 05:15:26 24 4
gpt4 key购买 nike

我刚刚开始研究一个非常基本的计算器程序,它运行良好,我无法让它在完成计算后保持程序打开。 io.read() 似乎不起作用。我的代码如下:

promptmethod = "Would you like to use addition, subtraction, multiplication, or           division?"
promptnumber1 = "Enter a number:"
promptnumber2 = "Enter another number:"
anotherprompt = "Would you like to make another calculation?"

print(promptmethod)
usermethod = io.read("*line")
print(promptnumber1)
number1 = io.read("*number")
print(promptnumber2)
number2 = io.read("*number")

if usermethod == "addition" then
answer = number1 + number2
stringanswer = "Your calculation is " .. number1 .. " + " .. number2 .. " = " .. answer
elseif usermethod == "subtraction" then
answer = number1 - number2
stringanswer = "Your calculation is " .. number1 .. " - " .. number2 .. " = " .. answer
elseif usermethod == "multiplication" then
answer = number1 * number2
stringanswer = "Your calculation is " .. number1 .. " × " .. number2 .. " = " .. answer
elseif usermethod == "division" then
answer = number1 / number2
stringanswer = "Your calculation is " .. number1 .. " ÷ " .. number2 .. " = " .. answer
else
error("Invalid operation or values.")
end

print(stringanswer)

io.read()

有谁知道为什么会发生这种情况?谢谢!

最佳答案

一个更简单的例子:

io.read('*number')
io.read()

问题是 read('*number')不消耗数字后的换行符。由于它仍然位于输入流上,所以当您调用 io.read 时(默认读取一行),它立即返回。

要解决这个问题,只需调用 io.read第二次。

关于lua - io.read() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14343502/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com