大家好,我是编程新手,并决定使用Project Euler来巩固我的知识。
我用以下方式尝试了问题2:
Option Explicit
Private Sub question2v2()
Dim val1 As Single
Dim val2 As Single
Dim counter As Single
Dim val3 As Single
Dim newval As Single
Dim lastval As Single
Dim intfin As Single ' sum of even values
Dim lenstr As Integer
val1 = 1
val2 = 1
Do While intfin < 4000000
val3 = val1 + val2
val1 = val2
val2 = val3
If val3 Mod 2 = 0 Then
newval = val3
intfin = lastval + newval
lastval = newval
Debug.Print intfin
End If
Loop
End Sub
我得到的是4,356,618,这个答案已接近答案,但并不完全存在。
请查看算法并告诉我出错的地方。
非常感谢您的帮助,谢谢!
答案 0 :(得分:1)
我认为您只需进行一项小改动,请在下面的代码中进行评论。我还收录了@ jsheeran的评论。
Private Sub question2v2()
Dim val1 As Long
Dim val2 As Long
Dim counter As Long
Dim val3 As Long
Dim newval As Long
Dim lastval As Long
Dim intfin As Long ' sum of even values
Dim lenstr As Long
val1 = 1
val2 = 1
Do While intfin < 4000000
val3 = val1 + val2
val1 = val2
val2 = val3
If val3 Mod 2 = 0 Then
newval = val3
intfin = lastval + newval
lastval = intfin 'changed from newval as intfin keeps the running total
Debug.Print intfin
End If
Loop
End Sub