Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Function 最大数查找器_Function_Lua_Numbers_Negative Number - Fatal编程技术网

Function 最大数查找器

Function 最大数查找器,function,lua,numbers,negative-number,Function,Lua,Numbers,Negative Number,这是我的代码,用于一个简单的程序,该程序在表中查找最大的数字,并返回该数字及其索引。我的问题是这个程序不能处理底片 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 =

这是我的代码,用于一个简单的程序,该程序在表中查找最大的数字,并返回该数字及其索引。我的问题是这个程序不能处理底片

 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”


谢谢

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

local maxcount = t[1]
local maxindex = 1
您收到“0零”是因为

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

  • 默认的
    maxcount
    值为0,大于所有负数


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

      local maxcount = t[1]
      local maxindex = 1
      
      您收到“0零”是因为

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

      • 默认的
        maxcount
        值为0,大于所有负数


      maxcount
      必须在开始时设置为大的负数,而不是零。尝试
      -math。开始时,必须将maxcount设置为大的负数,而不是零。试试数学。谢谢!为了获得正确的负片索引,我必须将maxindex设置为1而不是0。谢谢!为了得到正确的负片索引,我必须将maxindex设置为1而不是0。