Lua程序设计第4版第5章练习答案
程序员文章站
2024-03-17 23:01:04
...
5.1
monday sunday sunday
t.sunday => 表中sunday对应的值
t[sunday] =>sunday变量=>monday键([sunday]对应的值=>monday变量"sunday"
t[t.sunday]=>monday键同上
5.2
同一张表的引用 一样
引发异常 等同于把3当成表来用了
5.3
方括号内写索引值
5.4
每次多乘一个x,构造表达式 l[i]*x^i
function f54(l,x)
local sum = 0
local tmp = 1
for i = 1, #l do
sum = sum+l[i]*tmp
tmp = tmp*x
end
return sum
end
print(f54({5,2,3},2))
function f54(l,x,n)
local sum = 0
local tmp = 1
local cnt = -1
for i = 1, #l do
sum = sum+l[i]*tmp
cnt=cnt+1
print("cnt = "..cnt)
if cnt==n then
break
end
tmp = tmp*x
end
return sum
end
print(f54({5,2,3,4},2,2))
5.6
看最后一个元素的索引和表的长度是否相等
5.7
Pair迭代A表把元素插入到B表中
5.8
遍历使用新字符串拼接连接造成大量新字符串生成性能消耗、
计时方法 times= os.Clock() os.clock()-times
function concat(l)
s = ""
for k,v in pairs(l) do
s= s..v
end
return s
end
times1 = os.clock()
for i = 1, 1000000 do
concat({"hello"," ","world"})
end
print(os.clock()-times1)
times2 = os.clock()
for i = 1, 1000000 do
table.concat({"hello"," ","world"})
end
print(os.clock()-times2)
差异
0.681
0.454
上一篇: 【高精度模拟】POJ 1001 Exponentiation
下一篇: 非递归二分法查找