【问题标题】:Lua Max Number FinderLua 最大数查找器
【发布时间】:2012-07-25 18:17:06
【问题描述】:

这是我的一个简单程序的代码,它在表中找到最大的数字,并返回数字和它的索引。我的问题是该程序不适用于底片。

 numbers = {1, 2, 3}

 function largest(t)
   local maxcount = 0
   local maxindex
   for index, value in pairs(t) do
    if value > maxcount then
       maxcount = value
       maxindex = index
     end
   end
   return maxcount, maxindex
 end

 print(largest(numbers))

这段代码打印出“3 3”。最大的数字是 3,它在第 3 位。当我将数字设置为 {-1, -2, -3} 时,它返回“0 nil”而不是“-1 1”。

谢谢!

【问题讨论】:

    标签: function lua numbers negative-number


    【解决方案1】:

    您的默认值是错误的。 他们应该是

    local maxcount = t[1]
    local maxindex = 1
    

    您收到“0 nil”是因为

    • maxindex 未定义,直到 if 条件 value > maxcount 为真。

    • 默认的maxcount 值是0,它比所有的负数都大。

    【讨论】:

    • 谢谢!为了获得正确的负数索引,我必须将 maxindex 设置为 1 而不是 0。
    【解决方案2】:

    maxcount 在开始时必须设置为一个较大的负数,而不是零。试试-math.huge

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-04
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多