vb.net 如何获得偶数或奇数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24220929/
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-09 17:32:02  来源:igfitidea点击:

How to get even or odd numbers

vb.netvisual-studio-2010visual-studio-2012

提问by Didy

I don't know why this program doesn't works. I get a random number and the computer select what type it is even or odd ?

我不知道为什么这个程序不起作用。我得到一个随机数,计算机选择它是偶数还是奇数?

Dim a As New Random()

    Dim b As Integer
    Dim ca As Integer
    b = a.Next(0, 10)
    Debug.Print(b)

    ca = b / 2

    If ca = 0 Then
        Debug.Print("Even")
    Else
        Debug.Print("Odd")
    End If

回答by Marco

You are messing up your operators.

你在搞砸你的运营商。

You use division /, but you want to use the modulo operator Mod.

您使用除法/,但您想使用模运算符Mod

Please note: in C# it is %. In VB.Net it is Mod

请注意:在 C# 中它是%. 在 VB.Net 中是Mod

Reference: http://msdn.microsoft.com/en-us/library/se0w9esz(v=vs.100).aspx

参考:http: //msdn.microsoft.com/en-us/library/se0w9esz(v=vs.100).aspx

Dim a As New Random()
Dim b As Integer
Dim ca As Integer
b = a.Next(0, 10)
Debug.Print(b)

ca = b Mod 2

If ca = 0 Then
    Debug.Print("Even")
Else
    Debug.Print("Odd")
End If

Why your code does not work as expected: The culprit is indeed your if-statement. You are checking if the result of b / 2is 0. But this can only be true if bitself is 0. Every number greater then 0 devided by half is greater then zero.

为什么您的代码没有按预期工作:罪魁祸首确实是您的 if 语句。您正在检查的结果是否b / 2为 0。但只有当b它本身为 0时才为真。每个大于 0 的数字除以一半都大于零。

Your code looks like you want to check for the rest of a division, hence the solution with the modulo operator.

您的代码看起来像是要检查除法的其余部分,因此使用模运算符的解决方案。

回答by dbasnett

You could also just check the low order bit, if it is on the number is odd, if it is off the number is even. Using a function:

您也可以只检查低位,如果它在数字上是奇数,如果它不在数字上是偶数。使用函数:

    Dim a As New Random()
    Dim b As Integer
    b = a.Next(0, 10)
    Debug.WriteLine(b)
    If isEven(b) Then
        Debug.WriteLine("even")
    Else
        Debug.WriteLine("odd")
    End If

Private Function isEven(numToCheck As Integer) As Boolean
    Return (numToCheck And 1) = 0
End Function

edit: might be faster than mod but haven't checked.

编辑:可能比 mod 快,但尚未检查。

回答by Furygamerkeshav 007

Private sub command1_click()
   Dim a as integer
   a = text1.text
   If a mod 2=0 then
      Print a & " is even"
   Else
      Print a & "is odd"
   Endif
End sub