3 Dim i as integer s as integer

  • Slides: 29
Download presentation

例3: Dim i as integer, s as integer S=0:n=10 For i=1 to n step

例3: Dim i as integer, s as integer S=0:n=10 For i=1 to n step -1 s=s+i Next Label 1. caption=str(s) S=s+i语句共执行了几次? 程序执行完s的值是多少? 程序执行完i的值是多少? 0 0 1

例4: Dim i as integer, s as integer S=0:n=10 For i=1 to n s=s+I

例4: Dim i as integer, s as integer S=0:n=10 For i=1 to n s=s+I i=i+1 Next Label 1. caption=str(s) S=s+i语句共执行了几次? 程序执行完s的值是多少? 程序执行完i的值是多少? 5 25 11

例4: Dim x as integer, r as integer, s as string X=val(text 1. text)

例4: Dim x as integer, r as integer, s as string X=val(text 1. text) Do while x>0 r=x mod 2 s=r & s x=x2 loop

求a、b两数的最大公约数 方法一:辗转相除法代码一 If a<b then t=a: a=b: b=t r= a mod b Do while

求a、b两数的最大公约数 方法一:辗转相除法代码一 If a<b then t=a: a=b: b=t r= a mod b Do while r<>0 a=b b=r r=a mod b Loop label 1. caption=“最大公约数是” +str (b) 辗转相除法代码三 Do while b<>0 r=a mod b a=b b=r Loop label 1. caption=“最大公约数是” +str (a) 辗转相除法代码二 r=a mod b Do while r<>0 a=b b=r r= a mod b Loop label 1. caption=“最大公约数是” +str (b) 方法三:辗转相减法代码 Do While a <> b If a>b then a=a-b else b=b-a Loop Print a ‘ print b也一样

判断数a是否为素数 方法一: n = Val(Text 1. Text) f = True ‘ f=0 For i

判断数a是否为素数 方法一: n = Val(Text 1. Text) f = True ‘ f=0 For i = 2 To n-1 If n Mod i = 0 Then f = False ‘ f=1 Exit For End If Next I 方法二: n = Val(Text 1. Text) f = True For i = 2 To int(sqr(n)) If n Mod i = 0 Then f = False Exit For End If Next I If f = True Then ‘ if f= 0 then Label 1. Caption = Str(n) + "是素数" Else Label 1. Caption = Str(n) + "不是素数" End If If f = True Then Label 1. Caption = Str(n) + "是素数" Else Label 1. Caption = Str(n) + "不是素数" End If

自定义函数例二 ‘自定义判断一个数是否为偶数的函数 Function oushu(x As Integer) As Boolean If x mod 2= 0 Then

自定义函数例二 ‘自定义判断一个数是否为偶数的函数 Function oushu(x As Integer) As Boolean If x mod 2= 0 Then oushu = True Else oushu = False End If End Function Private Sub Command 1_Click() Dim a As Integer a = Val(Text 1. Text) If oushu(a) then Label 3. Caption = “是偶数” Else Label 3. Caption = “不是偶数” End if End Sub

自定义函数例三 '自定义函数求两数中的较大数 Function jd(x As Single, y As Single) As Single ‘多个形参 If x

自定义函数例三 '自定义函数求两数中的较大数 Function jd(x As Single, y As Single) As Single ‘多个形参 If x < y Then jd = y Else Private Sub Command 2_Click() jd = x Dim a As Single, b As Single, c As Single End If a = Val(Text 1. Text) End Function b = Val(Text 2. Text) c = Val(Text 3. Text) Label 4. Caption = “最大的数是" + Str(jd(jd(a, b), c)) ______ End Sub

自定义函数当过程用 Function swap(a As Single, b As Single) t = a: a = b:

自定义函数当过程用 Function swap(a As Single, b As Single) t = a: a = b: b = t End Function Private Sub Command 1_Click() Dim x As Single, y As Single x = Val(Text 1. Text) y = Val(Text 2. Text) Call swap(x, y) ‘过程调用 或者写成 swap x, y Label 3. Caption = “交换后x的值是:” + Str(x) + “,y的值是:" + Str(y) End Sub