zoukankan      html  css  js  c++  java
  • 关于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
  • 相关阅读:
    Java再学习——栈(stack)和堆(heap)
    Java再学习——深究static关键字
    毕业设计进度:3月4日
    毕业设计进度:3月3日
    可视化组件:echarts柱状图添加点击事件
    毕业设计进度:2月29日
    毕业设计进度:2月28日
    毕业设计进度:2月27日
    毕业设计进度:2月26日
    毕业设计进度:2月25日
  • 原文地址:https://www.cnblogs.com/guangshan/p/4501984.html
Copyright © 2011-2022 走看看