大家帮我看看VB代码啊,很简单的

来源:百度知道 编辑:UC知道 时间:2024/05/15 09:57:04
Private Sub Text1_KeyPress(KeyAscii As Integer)
On Error Resume Next
Dim n As Integer
Dim sum As Integer
Dim temp As Integer
sum = 0
If KeyAscii = 13 Then
For n = 1 To CInt(Text1.Text)
sum = sum + n
temp = (sum + n) ^ 2
Next
Label5.Caption = "1到" & n - 1 & "的平方和为" & CStr(temp)
End If
End Sub
是为了算出1到N的平方和
1^2+2^2+.......+n^2=n*(n+1)*(2n+1)/6
这个公式我也知道

你的程序计算的表达式错误,是计算了以下这条表达式:
(1+2+3+4+……+(n-1)+n+n)^2

如果你是想计算这个公式:1^2+2^2+.......+n^2,那么应该如下修改

Private Sub Text1_KeyPress(KeyAscii As Integer)
On Error Resume Next
Dim n As Integer
Dim sum As Integer
sum = 0
If KeyAscii = 13 Then
For n = 1 To CInt(Text1.Text)
sum = sum + n^2
Next
Label5.Caption = "1到" & n & "的平方和为" & CStr(sum)
End If
End Sub