基本上,我正在制作一个程序(供学校使用),用户输入一些球的体积,并使用一个公式来获取直径,然后查看直径是否太大。 但我的变量之一应该是球的名称,这样我就可以在输出中引用它(例如:你给我一个最大直径为 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/