2014-05-19 46 views
0

我試圖爲自己的用途創建一個計算器。我不知道如何製作,以便當用戶輸入例如6爲提示讓用戶鍵入6個數字。所以,如果我寫了7,它會給我寫的7個號碼,然後給我答案的選項,如果我寫了8它將讓我寫8號...帶計算器腳本的Lua

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

順便說一句,有點搞砸了,因爲我沒有完成它,所以像amountNmb變量代碼甚至不需要那裏等 – user3654336

+0

有沒有理由爲什麼沒有答案接受?這仍然是開放的嗎? – Schollii

回答

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) 

這不會限制值的計數任何特定的值 - 即使是空白列表也能正常工(這是有缺陷的,因爲它允許線結束與一個逗號,其將被忽略。)

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 
+0

謝謝,它的工作。 – user3654336

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'(不包括引號),然後print(total)給出64,正確答案