1

我的代码旨在读取数字并将其转换为中文拼音:

function digitconverter (digit)
    if digit == "0" then
        cnumber = "ying2 "
    elseif digit == "1" then
        cnumber = "yi1 "
    elseif digit == "2" then
        cnumber = "er2 "
    elseif digit == "3" then
        cnumber = "san1 "
    elseif digit == "4" then
        cnumber = "si4 "
    elseif digit == "5" then
        cnumber = "wu3 "
    elseif digit == "6" then
        cnumber = "liu4 "
    elseif digit == "7" then
        cnumber = "qi1 "
    elseif digit == "8" then
        cnumber = "ba1 "
    elseif digit == "9" then
        cnumber = "jiu3 "
    end
    return cnumber
end

print("Enter a number to be converted:")

repeat
    strnumber = io.read("*line")
    number = tonumber(strnumber)
    if number ~= nil then
        continue = true
    else
        print("Invalid input. Please try again:")
        continue = false
    end
until continue == true
nlength = #strnumber

digits = {}
for d in string.gmatch(number, "%d") do
    digits[#digits + 1] = d
end

convnumber = ""
for d=1,nlength do
    convnumber = convnumber .. digitconverter(digits[d])
end
print(convnumber)

    io.read()

如果我输入超过 15 位数字,它就会卡住(因为没有更好的术语)。它会转换每个数字,但第 16 位将是随机的,第 17 位及以后将重复另一个随机数字。我已经完成了它,但我无法弄清楚它挂在哪里。想法?

4

2 回答 2

8

您正在遍历number, not的数字strnumber。问题是当你得到太多数字时,字符串表示将采用科学计数法:

strnumber = '1234567890123456789'
number = tonumber(strnumber)
print(number) --> 1.2345678901235e+018

旁注:Lua 基于哈希表,它为您提供(除非哈希冲突)恒定时间查找。所以你的数字转换器可以简单地写成一张地图:

local digitmap = {
   ["0"] = "ying2 ",
   ["1"] = "yi1 ",
   ["2"] = "er2 ",
   ["3"] = "san1 ",
   ["4"] = "si4 ",
   ["5"] = "wu3 ",
   ["6"] = "liu4 ",
   ["7"] = "qi1 ",
   ["8"] = "ba1 ",
   ["9"] = "jiu3 ",
}

此外,像这样构建字符串效率非常低:

for d=1,nlength do
   convnumber = convnumber .. digitconverter(digits[d])
end

您正在生成大量中间字符串,这需要大量分配并产生大量垃圾。将需要连接的所有值放入表中,然后调用table.concat. 另一个优点是您可以指定分隔符(现在,您正在将分隔符硬编码到字符串表中)。

使用这些技术,我们可以像这样重写您的代码:

local digitmap = {
   ['0'] = 'ying2',
   ['1'] = 'yi1',
   ['2'] = 'er2',
   ['3'] = 'san1',
   ['4'] = 'si4',
   ['5'] = 'wu3',
   ['6'] = 'liu4',
   ['7'] = 'qi1',
   ['8'] = 'ba1',
   ['9'] = 'jiu3',
}

print('Enter a number to be converted:')
while true do
   strnumber = io.read('*line')
   if not strnumber:match('%D') then
      break
   end
   print('Invalid input. Please try again:')
end

local digits = {}
for digit in string.gmatch(strnumber, '%d') do
   digits[#digits + 1] = digitmap[digit]
end

print(table.concat(digits, ' '))
于 2013-01-30T00:33:04.797 回答
2

可能,您想扫描strnumber而不是number在代码的以下行中:

for d in string.gmatch(number, "%d") do

您的number变量包含double格式为 15-16 位十进制数字的数值。

于 2013-01-30T00:26:19.293 回答