关于VBS的一个怪现象

今天一个同学让我帮忙写一个程序,要求是:

输入一个n,返回从0到n中任意个数的组合,返回取异或结果为0的组合。来看VBS代码

n = 6
p = ""
for i = 0 to 2^n - 1
    s = 0
    for j = 0 to n-1
        s = s xor (j+1) * ((i and 2^j) / 2^j)
    next
    if s=0 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 = 0 then
       D2B = 0
     else
         Do While Dec > 0
             D2B = Dec Mod 2 & D2B
             Dec = Dec \ 2
         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 = 6
result = ""
for i = 0 to 2^n - 1
    s = 0
    for j = 0 to n-1
        s = s xor (j+1) * ((i and 2^j) / 2^j)
    next
    if s=0 then 
        temp = i
        result = result & D2B(temp) & chr(13) & chr(10)
    end if
next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("result.txt",2,true)
objFile.WriteLine result
Function D2B(Dec)
     if Dec = 0 then
       D2B = "0"
     else
         Do While Dec > 0
             D2B = Dec Mod 2 & D2B
             Dec = Dec \ 2
         Loop
       end if
       for k = 1 to n-len(D2B)
         D2B = "0" & D2B
       next
End Function

 

posted @ 2015-05-13 22:53  光闪  阅读(360)  评论(0编辑  收藏  举报