• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

有趣的Lua表

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

原文:http://lua-users.org/wiki/FunWithTables

题目:输出1到100之间的数哪些能被3整除,哪些能被5整除.

常规的做法是做一个从1到100的循环,让数模3和5,使用if else if这样语句进行判断.

for i = 1, 100 do
if i %3 == 0 and i % 5 == 0 then
print(i .. ' is divisible by both 3 and 5!')
elseif i % 3 ~= 0 and i % 5 ~= 0 then
print(i .. ' is not divisible by either 3 or 5!')
elseif i % 3 == 0 then
print(i .. ' is divisible by 3 only!')
elseif i % 5 == 0 then
print(i .. ' is divisible by 5 only!')
end
end

一个有趣的做法是使用表.因为一个数要么能被3整除要么不被3整除,要么被5整除要么不能整除.

那么一个数能否被3和5整除一共是4种情况.分别用true和false来表示能整除和不能整除,那么结果是:

能被3整除 对 能被5整除/不能被5整除

true 对 true/false)

能被5整除 对 能被3整除/不能被3整除

false 对 true/false

这相当于一个二维数组,第一维是两个元素:true或false ,第二维也是两个元素:true或false.

Lua处理数组是非常强大的,把他们放到表里就是:

{ ['true']={'true','false'} }

那么上述题目便有了如下的写法:

result={ 
[
true] = { [true] = ' is divisible by both 3 and 5!', [false ] = ' is divisible by 3 only!' },
[
false] = { [true] = ' is divisible by 5 only!', [false] = ' is not divisible by either 3 or 5!' }
}

for i=1,100 do
print(i .. result[i % 3 == 0][i % 5 == 0] )
end

其他演化的方法有:

-- common to both variants
local a, b, c, d =
" is not divisible by either 3 or 5",
" is divisible by 3 but not by 5",
" is divisible by 5 but not by 3",
" is divisible by both 3 and 5"

-- variant #1 --
local t = { a,b,c,d }
for x=1,100 do
print(x .. t[(x%3==0 and 1 or 0) + (x%5==0 and 2 or 0) + 1])
end

-- variant #2 --
for x=1,100 do
print(x .. (x%3==0 and (x%5==0 and d or b) or (x%5==0 and c or a)))
end

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Cocos2d-xLua中Sprite精灵类发布时间:2022-07-22
下一篇:
lua序列化(支持循环引用)发布时间:2022-07-22
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap