VB中用for循环求等比数列的和
就是求以1为首项,3为公比的等比数列的和。
要求用到VB中for循环。
刚学VB,希望不要给太难的代码。
感激不尽!
这个是我的代码,请大家帮忙修改一下。。。
Private Sub Command1_Click()
Dim n As Integer, i As Integer, s As Single, m As Integer
n = Val(Text1.Text)
For m = 1 To n
i = 3 ^ (m - 1)
s = s + i
Exit For
Next m
Text2.Text = s
End Sub
(n是让用户从文本框输入,m是拿来循环的) 展开
Private Sub Command1_Click()
Cls '清空窗口打印内容
n = Val(InputBox("n=")) '提示输入n值并把n值转换为数字类型
s = 1: s1 = 1 '设置计算结果和递乘3的函数初始值
t = " s=1+" '输出结果字符串初始内容
For i = 1 To n 'i从1循环到输入的n值
s1 = s1 * 3 '递乘以3
s = s + s1 '计算每个数字相加的结果
t = t & s1 '把递乘3的数字加入输出的字符串当中
If i < n Then '如果不是最后一个相加的数字就在输出字符串当中假如+号
t = t & "+"
End If
Next
Print t '在窗口中打印出结果字符串
Print "求:s=" & s '在窗口中打印出各个数相加的结果
End Sub
运行结果图片给你,每句代码也给你做了解释,请参考。
推荐于2017-08-01 · 知道合伙人教育行家
Private Sub Command1_Click()
Dim n As Integer, i As Integer, s As Integer, m As Integer
n = Val(Text1.Text)
s = 0
For m = 1 To n
i = 3 ^ (m - 1)
s = s + i
Next m
Text2.Text = s
End Sub
Private Sub Command1_Click()
Dim i As Long,Sum as Long
Dim m as integer,n as integer
n = inputbox("请输入一个数,表示等比数列的第n项。")
for m = 1 to n
i = 3 ^ (m-1)
sum = sum + i
Next
Print Sum
End Sub
麻烦您看一下我的问题补充,这里有字数限制问不了。。。
你的代码不应该加上Exit FOr语句,这个语句的作用是无条件退出For循环!
如果你加了这条语句,那么For语句就只能运行第一次!!
其他代码没有问题!!
Dim intSum As Integer
Dim n As Integer
Dim m As Integer
Dim intTotal As Integer
n = CInt(TextBox1.Text)
For intCount = 1 To (n - 1)
m = CInt(3 ^ intCount)
intSum = intSum + m
Next
intTotal = intSum + 1
TextBox2.Text = intTotal.ToString()