基本上,我有一个计算器,你可以选择除法,乘法,正负。我刚刚学会了如何循环程序。但是循环并没有正常工作。
print("Please choose the way to use the calculator")
print("[1] Plus [2] Minus [3] Division [4] Multiply")
restart = 1
x = tonumber(io.read())
while restart == 1 do
if x == 1 then
print("Please write the first number to add up")
n1 = tonumber(io.read())
print("Please write the second number to add up")
n2 = tonumber(io.read())
print(n1 .. "+" .. n2 .. "=" .. n1+n2)
elseif x == 2 then
print("Please write the first number to subtract")
n1 = tonumber(io.read())
print("Please write the second number to subtract")
n2 = tonumber(io.read())
print(n1 .. "-" .. n2 .. "=" .. n1-n2)
elseif x == 3 then
restart = 0
print("Please write the first number to divide")
n1 = tonumber(io.read())
print("Please write the second number to divide")
n2 = tonumber(io.read())
print(n1 .. "/" .. n2 .. "=" .. n1/n2)
elseif x == 4 then
print("Please write the first number to multiply")
n1 = tonumber(io.read())
print("Please write the second number to multiply")
n2 = tonumber(io.read())
print(n1 .. "*" .. n2 .. "=" .. n1*n2)
end
end所以,基本上,如果你选择负值,然后放进10-2。它应该起作用的。但问题是,只有负部分保持循环。它并不要求你选择一种繁衍方式。我怎么才能解决这个问题?
我想让它为你做这个方程,然后循环到开头。
发布于 2013-12-05 14:25:32
你可以把这个替换一下:
print("Please choose the way to use the calculator")
print("[1] Plus [2] Minus [3] Division [4] Multiply")
restart = 1
x = tonumber(io.read())
while restart == 1 do通过这一点:
restart = 1
while restart == 1 do
print("Please choose the way to use the calculator")
print("[1] Plus [2] Minus [3] Division [4] Multiply")
x = tonumber(io.read())另外,由于您正在学习Lua,这里有一种方法可以重构此代码(适当地使用本地语言等):
local get_operands = function(s)
print("Please write the first number to " .. s)
local n1 = io.read("*n")
print("Please write the second number to " .. s)
local n2 = io.read("*n")
return n1, n2
end
while true do
print("Please choose the way to use the calculator")
print("[1] Plus [2] Minus [3] Division [4] Multiply")
local x = io.read("*n")
if x == 1 then
local n1, n2 = get_operands("add up")
print(n1 .. "+" .. n2 .. "=" .. n1+n2)
elseif x == 2 then
local n1, n2 = get_operands("subtract")
print(n1 .. "-" .. n2 .. "=" .. n1-n2)
elseif x == 3 then
local n1, n2 = get_operands("divide")
print(n1 .. "/" .. n2 .. "=" .. n1/n2)
break
elseif x == 4 then
local n1, n2 = get_operands("multiply")
print(n1 .. "*" .. n2 .. "=" .. n1*n2)
end
end发布于 2013-12-05 12:22:19
你不需要把输入放进你的循环里吗?
x = tonumber(io.read())
while restart == 1 do应该是
while restart == 1 do
x = tonumber(io.read())发布于 2013-12-05 16:14:22
在循环之外设置x,这样它就不会改变。将x=输入放入循环中,这样每次迭代都会重新读取它。
https://stackoverflow.com/questions/20399818
复制相似问题