如何从输入表中创建输出表- Lua?

我需要帮忙修复我的代码。由于我未完成第9个问题。

Q:请填写if_then_elseif()函数,使用for循环和if then else语句创建所需的数组。目标是创建与输入表等效的输出表,如下对应关系所示 {"1", "2", "3", "4", "5", "6", "7", "8", "9"} =>> {"a", "b", "c", "d", "e", "f", "n", "n", "n"} ]]

require "testwell"

function foo(arg)
  --arg是数字表
  local out = {}
  local n = #arg
  --在这里放置代码 ****************
 for i = 1,#arg,1 do
  if i==1 then out[i] = "a"
    elseif i==2 then out[i] = "b"
     elseif i==3 then out[i]= "c"
      elseif i==4 then out[i] = "d"
       elseif i==5 then out[i]= "e"
        elseif i==6 then out[i] = "f"
         elseif i==7 then out[i] = "n"
          elseif i==8 then  out[i]= "n"
           elseif i==9 then out[i] = "n"
          else print("无效输入")

end
end
  -- 和 **********************************
  return out
end

is(foo({1,2}), {"a", "b"}, '数字转字母 1')
is(foo({1,2,3}), {"a", "b", "c"}, '数字到字母 2')
is(foo({1,2,3,4}), {"a", "b", "c", "d"}, '数字转字母 3')
is(foo({1,2,3,4,5}), {"a", "b", "c", "d", "e"}, '数字到字母 4')
is(foo({1,2,3,4,5,6}), {"a", "b", "c", "d", "e", "f"}, '数字到字母 5')
is(foo({1,2,3,4,5,6,7}), {"a", "b", "c", "d", "e", "f", "n"}, '数字到字母 6')
is(foo({1,2,3,4,5,6,7,8}), {"a", "b", "c", "d", "e", "f", "n", "n"}, '数字到字母 7')
is(foo({1,2,3,4,5,6,7,8,9}), {"a", "b", "c", "d", "e", "f", "n", "n", "n"}, '数字到字母 8')
is(foo({9,8,7,6,5,4,3,2,1}), {"n", "n", "n", "f", "e", "d", "c", "b", "a"}, '数字转字母(反转)')
报告()
``````````````````````
我收到的输出是
`````````
程序'lua.exe''C:\Users\Marian\Downloads\ZeroBraneStudio\myprograms'(pid:6032)中启动。
ok 1 - 数字转字母 1
ok 2 - 数字到字母 2
ok 3 - 数字转字母 3
ok 4 - 数字到字母 4
ok 5 - 数字到字母 5
ok 6 - 数字到字母 6
ok 7 - 数字转字母 7
ok 8 - 数字转字母 8
未通过的测试9号-数字转字母(反转)
#    在... \ ZeroBraneStudio \ myprograms \ 290-A2 \ 05-e-if then else.lua 第54行的 '数字转字母(反转)'!
#          得到:{"a", "b", "c", "d", "e", "f", "n", "n", "n"} (table)
#    预期的是:{"n", "n", "n", "f", "e", "d", "c", "b", "a"} (table)
1..9#看起来您通过了8个测试,失败了1个测试(8/0/9)。
程序完成,用时0.17秒(pid:6032)。
`````````````````````
点赞
用户6632736
用户6632736

我的个人建议:

function foo( arg )
    --arg 是数字的表
    local map = {'a', 'b', 'c', 'd', 'e', 'f', 'n', 'n', 'n'}
    local out = {}
    local n = #arg -- 不需要。
 - 在这里放置您的代码 **************** -
    for key,value in对(argdo中的对中,注意关联即arg也用于处理。
        out [key] = map [value] or打印“无效输入” -没有需要的if。
    end
    - 并在这里 ********************************-
    返回输出
end

但是如果您必须使用“if”和“arg”是一个纯索引数组:

function foo( arg )
    --arg 是数字的表
    local out = {}
    local n = #arg
 - 在这里放置您的代码 **************** -
    for i = 1,n的do
        如果arg [i] == 1,则out [i] ='a'
        elseif arg [i] == 2 then out [i] ='b'
        elseif arg [i] == 3 then out [i] ='c'
        elseif arg [i] == 4 then out [i] ='d'
        elseif arg [i] == 5 then out [i] ='e'
        elseif arg [i] == 6 then out [i] ='f'
        elseif arg [i] == 7arg [i] == 8arg [i] == 9 then out [i] ='n'
        else打印'无效输入'end
    end
    - 并在这里 ********************************-
    返回输出
end

P.S.我希望您的老师不要阅读StackOverflow。

2020-09-27 15:05:43