尝试从用户获取一个值并将其递增。

我是编程新手,正在学习一些基本的技巧。现在我遇到的问题是:我正在尝试运行一个代码,让用户输入一个名字并将其打印在屏幕上,它运行得很好。所以我现在想加入一个特殊的部分,让用户输入要在屏幕上打印名字的数量,但当我这样做时它开始了一个无限循环,直到我关闭程序才停止。

这是代码:

function metodoDois()
  print("输入一个名字:")
  name = io.read();
  print("输入要在屏幕上打印多少次的名字:")
  quantidade = io.read()

  k = 0;
  while name do
    k = k + 1;
    io.write("\n", name, " ", k)
    if k == quantidade then
      name = not name;
    end
  end
end

metodoDois()
点赞
用户4211279
用户4211279

通常,为了重复计算一个已知数量的次数,使用for循环。因此,如果您没有特定的原因使用while循环,那么可以使用以下代码:

function metodoDois()
   print("Write a name:")
   local name = io.read()
   print("Write how many times that it will be printed on screen:")
   local quantidade = io.read()

   for k = 1, quantidade do
      io.write("\n", name, " ", k)
   end

end

metodoDois()

这样,您就避免了显式创建控制变量k和在每次迭代中进行测试以确定何时结束它。实际上,在for-循环中控制变量k会自动更新每次迭代时的值,使得循环在该变量获得其最终值时结束。 此外,kfor-循环的 _本地_变量(即,在其之前或之后它不存在),使得代码更易读,且减少了错误的可能性(请参阅 Lua 参考中的Local Variables and Blocks)。

2015-07-10 19:14:16
用户5101989
用户5101989

问题在于你的"quantidade"变量被读取为一个字符串,而你的"k"变量是一个数字。数字和字符串不同,所以,例如,1"1"不同。

要解决这个问题,只需先使用tonumber()函数将存储在"quantidade"变量中的读取转换为数字,即将quantidade = io.read()更改为quantidade = tonumber(io.read()),如下所示:

function metodoDois()
    print("Write a name: ")
    name = io.read();
    print("Write how many times that it will be printed on screen: ")
    quantidade = tonumber(io.read())
    k = 0;

    while name do
        k = k+1;
        io.write("\n", name, " ", k)
        if k == quantidade then
            name = not name;
        end
    end
end

metodoDois()

此外,这只是一个小问题,但是那段代码看起来有些没有被优化!我建议使用更像这样的代码:

function metodoDois()
    print("Write a name: ")
    local name = io.read();
    print("Write how many times that it will be printed on screen: ")
    local quantidade = tonumber(io.read())

    for k = 1, quantidade do
        io.write(name.." "..k.."\n")
    end
end

metodoDois()
2015-07-10 19:21:28