求前n项的和【VB代码实现】
求的和。
For语句实现
Private Sub Command1_Click() Dim s As Long '变量s表示存储前i项的和 Dim n As Integer Dim i As Integer '变量i表示第i项 n = Val(Text1.Text) s = 0 '变量s初始化为0 For i = 1 To n 'For循环的含义:计算求出前i项的和 s = s + i '通项公式 Next i Label4.Caption = Str(s) End Sub
Do While语句实现
Private Sub Command1_Click() Dim s As Long, i As Integer, n As Integer n = Val(Text1.Text) s = 0 i = 1 Do While i <= n s = s + i i = i + 1 Loop Label4.Caption = Str(s) End Sub
学习要求:
1、读懂题意,根据每一项的变化写出通项公式。
2、设定相应的变量来解决问题,理解各变量的作用。