今天一个同学让我帮忙写一个程序,要求是:
输入一个n,返回从0到n中任意个数的组合,返回取异或结果为0的组合。来看VBS代码
n =
p = ""
for i = to ^n -
s =
for j = to n-
s = s xor (j+) * ((i and ^j) / ^j)
next
if s= then
D2B(i)
end if
next
'Set objFSO = CreateObject("Scripting.FileSystemObject")
'Set objFile = objFSO.OpenTextFile("result.txt",2,true)
'objFile.WriteLine result
Function D2B(Dec)
if Dec = then
D2B =
else
Do While Dec >
D2B = Dec Mod & D2B
Dec = Dec \
Loop
end if
msgbox D2B
End Function
恩,很短小的代码,但是怪就怪在下面那个函数上了,上面代码这样
if s=0 then
D2B(i)
end if
时,输出结果没有问题,很正常。
但是当把代码改为:
if s=0 then
result = D2B(i)
end if
结果就不正常了。使用
Wscript.exe /X E:\debug.vbs
调试,结果发现是由于参数i传进函数为byref的,所以在函数内部对i做出了改变,于是就死循环了。但是为什么不对函数结果赋值是就没问题呢?待研究
(vb默认byref,vb.net默认byval)
一个很全的VBS博客了给出了解释。。。
标题: VBS过程和函数参数传递的方式默认是ByVal还是ByRef?
作者: Demon
链接: http://demon.tw/programming/vbs-byval-byref.html
果然有盲点啊
附完整版代码:
n =
result = ""
for i = to ^n -
s =
for j = to n-
s = s xor (j+) * ((i and ^j) / ^j)
next
if s= then
temp = i
result = result & D2B(temp) & chr() & chr()
end if
next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("result.txt",,true)
objFile.WriteLine result
Function D2B(Dec)
if Dec = then
D2B = ""
else
Do While Dec >
D2B = Dec Mod & D2B
Dec = Dec \
Loop
end if
for k = to n-len(D2B)
D2B = "" & D2B
next
End Function