关于一个VB程序的问题

来源:百度知道 编辑:UC知道 时间:2024/05/16 05:58:26
Option Explicit
Dim a As Single
Private Sub command1_click()
Dim a As Single, b As Integer
a = 1.2: b = 3
Print fun1(a, b)
Print a
End Sub
Private Function fun1(x As Single, y As Integer) As Integer
Dim i As Integer
For i = 1 To y
x = x * 2
a = a + 1
Next i
fun1 = a
End Function
为什么程序运行下来第一个结果是3?底下的a为什么和上面的a不一样啊?
为什么在第一次运算时a=a+1中a的初值是0啊?

这是因为在窗体里定义了a为全局变量,但是在command1中又定义了一个a为局部变量,所以在command1的过程中就把全局变量的a给屏蔽了。而在fun1过程中,a还代表的是全局变量的a调用fun1的时候把a=1.2,b=3传给了x,y.这是地址传递。其实是把局部变量a和b的地址传给了x,y所以计算完后。改变的是局部变量a,b的值。

在 for循环里循环三次。因为x初值为1.2所以三次后为9.6.

这里的 a是全局变量的a初值没有设置所以是0加三次1
后为3
所结果是3和9.6

这里要学的是,如果定义了全局变量。又在过程或函数里定义了同明的变量,那么该局部变量的值就会屏蔽全局变量。

Print fun1(a, b)
Print a
你编写的函数 Private Function fun1(x As Single, y As Integer) As Integer
其中的x y 在调用时使用的变量是a,b 这个是按变量在内存的地址传参
在函数中如果x 和 a 指向是同一个地址 所以a,b 改变了
如果改成Private Function fun1(byval x As Single,byval y As Integer) As Integer
指明参数传递是传值 调用函数后a 值不变
Private Function fun1(x As Single, y As Integer) As Integer
运行结果是
3
9.6
Private Function fun1(byval x As Single,byval y As Integer) As Integer
运行结果是
3
1.2

可以参考http://zhidao.baidu.com/question/29185484.html