1

我有一个需要用户提供两个整数的 Visual Basic 程序。

我需要能够显示用户输入的两个整数之间的偶数之和。如果用户的输入是偶数,它应该包含在总和中。

我无法弄清楚算法。

这是我的代码:

Public Class frmMain

Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
    Me.Close()
End Sub

Private Sub txtFirstNum_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtFirstNum.KeyPress
    ' allows the text box to accept only numbers, and the Backspace key

    If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso
        e.KeyChar <> ControlChars.Back Then
        e.Handled = True
    End If
End Sub

Private Sub txtSecondNum_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtSecondNum.KeyPress
    ' allows numbers and Backspace only

    If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso
        e.KeyChar <> ControlChars.Back Then
        e.Handled = True
    End If
End Sub

Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
    ' display the sum of even numbers

    ' declarations
    Dim intFirstNum As Integer
    Dim intSecondNum As Integer

    ' convert string to number with TryParse method
    Integer.TryParse(txtFirstNum.Text, intFirstNum)
    Integer.TryParse(txtSecondNum.Text, intSecondNum)

    ' find the even numbers
    If intFirstNum Mod 2 = 0 Then

    ElseIf intFirstNum Mod 2 = 1 Then

    End If

    ' add the even numbers

    ' display the result

End Sub
End Class

我怎样才能解决这个问题?

4

3 回答 3

2

您可以计算有多少个偶数,并从中计算总和:

' adjust the numbers to the closest even number
If (intFirstNum mod 2) = 1 Then intFirstNum += 1
If (intSecondNum mod 2) = 1 Then intSecondNum -= 1

' determine how many even numbers there are in the range
Dim count As Integer = (intSecondNum - intFirstNum) \ 2 + 1

' the sum is the average times the count
Dim sum As Integer = (intFirstNum + intSecondNum) * count \ 2

这些TryParse方法返回一个布尔值,它告诉您是否可以解析字符串。您不应忽略返回值,因此将其用作:

If Integer.TryParse(txtFirstNum.Text, intFirstNum) Then
  ' yes, it was a number
End If
于 2013-09-14T22:14:40.110 回答
1

如果您知道第一个数字是偶数,则在开始时检查,您不必检查每个数字的模数,只需增加 2s:

Public Function SumEvenNumbers(ByVal Start As Integer, ByVal End As Integer) As Integer
    If Start Mod 2 = 1 Then Start += 1

    Dim Result As Integer = 0
    While Start <= End
       Result += Start
       Start += 2
    End While

    Return Result
End Function

只是为了好玩,这是一个使用 linq 和 Enumerable.Range 的示例:

Public Function SumEvenNumbers(ByVal Start As Integer, ByVal End As Integer) As Integer
     If Start Mod 2 = 1 Then Start += 1
     Return Enumerable.Range(Start, End - Start).Sum(Function(i) i Mod 2 == 0)
End Function

但是最好的答案是已经发布的答案,并且只是使用 Math 将其全部减少到一个固定的平均值( O(1),而不是 O(n) )。

于 2013-09-15T00:29:38.863 回答
-1
Public Function GetEvenNumberSum(min As Integer, max As Integer) As Integer
    Dim sum As Integer = 0
    For i As Integer = min To max
        If i Mod 2 = 0 Then
            sum += i
        End If
    Next
    Return sum
End Function
于 2013-09-14T21:57:15.480 回答