内容正文:
7/28/2021
函数2——自定义函数
7/28/2021
自定义函数语法
Function 函数名(参数) As 函数返回值类型
语句......
End Function
思考:所定义的函数应该放在代码中的什么位置?
应放在通用里,因为它将被其他过程调用,即跨越过程,有全局意义
函数定义中应包含对函数名的赋值(即应返回的函数值)
7/28/2021
自定义函数例子
Function max(a As Single, b As Single, c As Single) As Single '定义函数max()
Dim m As Single
If a > b Then
m = a
Else
m = b
End If
If m > c Then
max = m
Else
max = c
End If
End Function
Private Sub Command1_Click()
Dim x As Single, y As Single, z As Single, m As Single
x = Val(Text1.Text): y = Val(Text2.Text): z = Val(Text3.Text)
Label1.Caption = "最大值为:" & Str(max(x, y, z)) '调用函数max()
End Sub
判断闰年问题
Function Leap(n As Integer) As Boolean '函数定义
If n Mod 400 = 0 Or n Mod 100 <> 0 And n Mod 4 = 0 Then
Leap = True
Else
Leap = False
End If
End Function
Private Sub Command1_Click() '函数调用
Print Leap (Val(Text1.Text))
End Sub
7/28/2021
习题『高考2010年3月卷』:按下面公式计算y的值:现要求编写VB程序(运行界面如下图),实现如下功能:在文本框txtInput中输入x的值,单击“计算”按钮Comma