function back(table1,table2) local a,b=0,0 for i=0,#table1 do for j=0,#table2 do if table2[j]==table[i] then a=a+1 if i==j then ? b=b+1 end end end end return a,bend該段代碼功能:比較兩個表中相同元素個數(代碼中a)和相同元素且下標相同的個數(代碼中b),如table1={1,2,3,4},table2={1,3,5,4}則a=3,b=2問題:a,b返回值總是等于0
1 回答

慕瓜5323351
TA貢獻1條經驗 獲得超1個贊
總共有兩處錯誤:第一lua表的下標是從1開始而不是從0;第二if table2[j]==table[i]這里錯了,table[i]改成table1[i]才對
function back(table1,table2)
?local a,b=0,0
?for i=1,#table1 do
??for j=1,#table2 do
???if table2[j]==table1[i] then
????a=a+1
????if i==j then
?????b=b+1
????end
???end
??end
?end
?return a,b
end
table1={1,2,3,4}
table2={1,3,5,4}
t1,t2=back(table1,table2)
print(t1,t2)
- 1 回答
- 0 關注
- 2416 瀏覽
添加回答
舉報
0/150
提交
取消