怎么在VB语言中给函数过程传递参数?
- 提问者网友:送舟行
- 2021-08-16 18:36
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
- 五星知识达人网友:旧脸谱
- 2021-08-16 18:53
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
- 1楼网友:傲气稳了全场
- 2021-08-16 22:40
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
- 2楼网友:纵马山川剑自提
- 2021-08-16 21:27
给函数过程传递实参 有两种方式 一种是传地址 (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了。
- 3楼网友:骨子里都是戏
- 2021-08-16 20:53
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
- 4楼网友:行路难
- 2021-08-16 20:26
你的程序有点小错误,帮你改好了。
定义变量有多余的,变量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
图: