vb.net 显示两个整数之间偶数的和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18806719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 15:04:30  来源:igfitidea点击:

Display the sum of the even numbers between two integers

vb.net

提问by Zack

I have a Visual Basic program that expects two integers from the user.

我有一个 Visual Basic 程序,它需要来自用户的两个整数。

I need tobe able to display the sum of the even numbers between the two integers entered by the user. If the user's entry is even, it should be included in the sum.

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

I am having trouble figuring out the algorithm.

我在弄清楚算法时遇到了麻烦。

Here is my code:

这是我的代码:

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

How can I fix this?

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

回答by Guffa

You can calculate how many even numbers there are, and from that calculate the sum:

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

' 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


The TryParsemethods returns a boolean, which tells you if it was possible to parse the string. You shouldn't ignore the return value, so use it as:

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

If Integer.TryParse(txtFirstNum.Text, intFirstNum) Then
  ' yes, it was a number
End If

回答by Joel Coehoorn

If you know the first number is even by checking that at the start, you don't have to check the modulus of every digit along the way, and can just increment by 2s:

如果您知道第一个数字甚至是通过在开始时检查它,您就不必在此过程中检查每个数字的模数,只需增加 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

And just for fun, here's an example that uses linq and Enumerable.Range:

只是为了好玩,这里有一个使用 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

But the best answer is the one that's already posted, and just uses Math to reduce it all to a fixed average ( O(1), rather than O(n) ).

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

回答by David Khuu

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