还是for语句的题。。真是很难阿~

来源:百度知道 编辑:UC知道 时间:2024/06/05 14:38:27
private function f(m as integer)
if m mod 2=0 then
f=m
else
f=1
end if
end funtion

private sub command1_click()
dim i as integer
s=0
for i =1 to 5
s=s+f(i)
next
print s
end sub
为虾米结果是:9

Private Function f(m As Integer)
If m Mod 2 = 0 Then '当m/2余0时为True
f = m '能被2整除,则返回原值,
Else
f = 1 '不能被2整除,则返回1
End If
End Function

Private Sub command1_click()
Dim i As Integer
s = 0
For i = 1 To 5 '1 3 5不能除尽,返回 1 1 1 ;2 4 能除尽,返回 2 4 。1+1+1+2+4=9
s = s + f(i)
Next

这个过程private function f(m as integer)的作用是
如果i对2取余为0的f=i,否则f=1;

结果如下:

当i=1是f=1
当i=2是f=2
当i=3是f=1
当i=4是f=4
当i=5是f=1

1+2+1+4+1=9

运用到函数调用
i=1,f(1)=1,s=1;
i=2,f(2)=2,s=1+2=3
i=3, f(3)=1,s=3+1=4
i=4, f(4)=4,s=4+4=8
i=5, f(5)=1,s=8+1=9
所以结果等於9