我正在尝试为自己创建一个计算器。我不知道如何制作它,以便当用户输入例如6为提示允许用户输入6个数字。因此,如果我写了7,它会给我一个选项来写7个数字,然后给我答案,如果我写了8,它会让我写8个数字......
if choice == "2" then
os.execute( "cls" )
print("How many numbers?")
amountNo = io.read("*n")
if amountNo <= 2 then print("You cant have less than 2 numbers.")
elseif amountNo >= 14 then print("Can't calculate more than 14 numbers.")
elseif amountNo <= 14 and amountNo >= 2 then
amountNmb = amountNo
if amountNmb = 3 then print(" Number 1")
print("Type in the numbers seperating by commas.")
local nmb
print("The answer is..")
答案 0 :(得分:0)
io.read
格式有点限制。
如果你想要输入以逗号分隔的列表,我建议读一整行,然后遍历每个值:
local line = io.input("*l")
local total = 0
-- capture a sequence of non-comma chars, which then might be followed by a comma
-- then repeat until there aren't any more
for item in line:gmatch("([^,]+),?") do
local value = tonumber(item)
-- will throw an error if item does not represent a number
total = total + value
end
print(total)
这不会将值的数量限制为任何特定值 - 即使空列表也可以。 (它有缺陷的是它允许行以逗号结束,这将被忽略。)
答案 1 :(得分:0)
根据我的理解,您want the following:
print "How many numbers?"
amountNo = io.read "*n"
if amountNo <= 2 then
print "You can't have less than 2 numbers."
elseif amountNo >= 14 then
print "Can't calculate more than 14 numbers."
else
local sum = 0
for i = 1, amountNo do
print( ('Enter number %s'):format(i) )
local nmb = io.read '*n'
sum = sum + nmb
end
print( ('The sum is: %s'):format(sum) )
end
答案 2 :(得分:0)
如果用户用逗号分隔数字,他们不需要说明他们想要添加的数量,您可以使用gmatch获取所有数字。使用正确的模式,您可以确保只获得数字:
local line = io.input()
local total = 0
-- match any number of digits, skipping any non-digits
for item in line:gmatch("(%d+)") do
total = total + item
end
输入&#4; 6,1,9,10,34&#39; (没有引号),然后print(total)
给出64,正确答案