for-loop - 我收到一条错误消息,指出我的 'for' 限制不是数字,即使我没有引用该变量

标签 for-loop lua stdin

基本上,我正在制作一个程序(供学校使用),用户输入一些球的体积,并使用一个公式来获取直径,然后查看直径是否太大。 但我的变量之一应该是球的名称,这样我就可以在输出中引用它(例如:你给我一个最大直径为 2 厘米的乒乓球。然后你给我球的数量通过程序运行,3。然后你给出3个卷,1.5,2.5和2 - 输出1.5 - 乒乓球,2.5 - 不是乒乓球,2 - 乒乓球)但是每当我运行我的程序时,我都会给出我的球的名称我收到一条错误消息,指出我的“for”限制不是数字,即使我不是指该变量而是指另一个变量。

local n = io.read("*n")  -- amount of balls 
for getal1 = 1, n do
  local naam_Bal = io.read() -- here I get an error if I enter a string
  local av = io.read("*n")  -- amount of volumes for the type of ball
  local gewenste_Diameter = io.read("*n")  -- maximum diameter
  local volume
  local diameter
  for getal2 = 1, av do
    volume = io.read("*n")   -- volume for each ball
    diameter = 2 * (((3/4)*(volume/math.pi)) ^ (1/3))  -- formula to calculate the diameter
    print(diameter)
  end 
end

这可能是一个愚蠢的错误,但我真的陷入困境

最佳答案

这是因为 io.read("*n") 未读取 EOL(数字后面)。

脚本中实际发生的情况:

  • local n = io.read("*n") 读取数字,但未读取 EOL。
  • local naam_Bal = io.read() 读取前一个编号的 EOL,但不读取名称。
  • local av = io.read("*n") 读取名称。

解决方案:
如果每个数字都在单独的输入行上,
您应该始终使用 io.read("*n", "*l") 而不是 io.read("*n")

关于for-loop - 我收到一条错误消息,指出我的 'for' 限制不是数字,即使我没有引用该变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66280150/

相关文章:

c++ - 对于 C++ 中的次要或相等条件

java - java 中的错误 - 查找 ArrayList 中的最大值

algorithm - 使用递归方法查找接近路径或区域

algorithm - 关于算法的一点提示

stdin - wget -i - ./目录

c - 处理后 stdin 到 stdout

java - 第一个字符在字符串中出现多少次

performance - MATLAB 向量化 : creating a cell array of neighbor index arrays

function - 如何在Lua中将函数作为参数传递?

python - 连接到服务器时获取标准输入 Python