当前位置:编程学习 > VB >>

怎么在VB语言中给函数过程传递参数?

我编写的一段程序在VB语言中给函数过程传递参数?
Private Sub Form_Click()
Dim s As Integer, x As Integer, y As Integer
Dim n, p, q As Integer
s = 5
x = 2
y = 3
a = myfunc(s, x, y)
Print "第" & 5 & "项是"; a
End Sub
Function myfunc(s As Integer, x As Integer, y As Integer)
If s = 1 Then
myfunc = x
ElseIf s = 2 Then
myfunc = y
Else
myfunc = myfunc(s - 2) + myfunc(s - 1)
End If
End Function
追问:你QQ细谈关键函数过程传递参数我没弄明白

 

 

答案:Private Sub Form_Click()
 Dim s As Integer
 Dim x As Integer
 Dim y As Integer
 s = 5
 x = 2
 y = 3
 a = myfunc(s, x, y)
   Print "第" & 5 & "项是:" & a
End Sub
Function myfunc(ByVal s As Integer, ByVal x As Integer, ByVal y As Integer)
   If s = 1 Then
      myfunc = x
 ElseIf s = 2 Then
      myfunc = y
 Else
      myfunc = myfunc(s - 2, x, y) + myfunc(s - 1, x, y)
End If
End Function
上述的代码在遍历中,其中有五次是符合计算要求的

第一次的值是:2

第二次的值是:3

第三次的值是:3

第四次的值是:2

第五次的值是:3

     即2+3+3+2+3=13

 

你的程序有点小错误,帮你改好了。

定义变量有多余的,变量a未定义,这是一个递归的调用,

调用时,参数的个数要相等,你这一句:myfunc = myfunc(s - 2) + myfunc(s - 1)

才给了一个参数,看我该好的正确的代码:

 


Private Sub Form_Click()
Dim s As Integer, x As Integer, y As Integer
Dim a As Integer
s = 5
x = 2
y = 3
a = myfunc(s, x, y)
Print "第5项是"; a
End Sub
Function myfunc(s As Integer, x As Integer, y As Integer)
If s = 1 Then
myfunc = x
ElseIf s = 2 Then
myfunc = y
Else
myfunc = myfunc(s - 2, x, y) + myfunc(s - 1, x, y)
End If
End Function

 

 

图:

 


Option Explicit

Private x, y As Integer 'x为第一项值,y为第二项值

Private Sub Form_Click()
    Dim s, a As Integer
   
    s = 5
    x = 2
    y = 3
   
    a = myfunc(s)
    Print "第" & s & "项是" & a
End Sub
Function myfunc(ByVal s As Integer)
    If s = 1 Then
        myfunc = x
    ElseIf s = 2 Then
        myfunc = y
    Else
        myfunc = myfunc(s - 2) + myfunc(s - 1) '递归调用
    End If
End Function

 

给函数过程传递实参 有两种方式 一种是传地址  (by ref)另一种是传值(by val),如果采用传地址那么 结果 实参和形参 都一样了,也就是在一些程序中,不可以用。 传值就不影响了。下面举例说明怎么传

private function(by val,x as integer,y as integer)as integer  '这里我建立了一个function 函数过程 形参x是整型数,形参y也是整型数。算出来的最后结果也是整型数。

s=x+y  '这里把 x+y 赋给了s

end function

你想要调用的时候 就用下面两种语句都可以

一 function 2,3   二call function (2,3) 注意这里把实参 2和三分别传给了 x和y,调用了function过程来计算结果是 s=2+3     ,现在是就赋值为5了。

Private Sub Form_Click()
Dim s As Integer, x As Integer, y As Integer
Dim n, p, q As Integer
s = 5
x = 2
y = 3
a = myfunc(s, x, y)
Print "第" & 5 & "项是"; a
End Sub
Function myfunc(s As Integer, x As Integer, y As Integer) As Long
If s = 1 Then
myfunc = x
ElseIf s = 2 Then
myfunc = y
Else
myfunc = myfunc + (s - 2) + (s - 1)
End If
End Function

 

上一个:关于在VB中查询ACCESS表的问题,求教。
下一个:VB语句问题(VB高手请进!!!)

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,