如何获得偶数或奇数 [英] How to get even or odd numbers
问题描述
我不知道为什么这个程序不起作用.我得到一个随机数,计算机选择它是偶数还是奇数?
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
推荐答案
你在搞砸你的操作员.
您使用除法 /
,但您想使用模运算符 Mod
.
You use division /
, but you want to use the modulo operator Mod
.
请注意:在 C# 中它是 %
.在 VB.Net 中它是 Mod
Please note: in C# it is %
. In VB.Net it is Mod
参考: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
为什么您的代码没有按预期工作:罪魁祸首确实是你的 if 语句.您正在检查 b/2
的结果是否为 0.但这只能在 b
本身为 0 时为真.每个大于 0 的数字除以一半都大于零.
Why your code does not work as expected:
The culprit is indeed your if-statement. You are checking if the result of b / 2
is 0. But this can only be true if b
itself is 0. Every number greater then 0 devided by half is greater then zero.
您的代码看起来像是要检查除法的其余部分,因此使用模运算符的解决方案.
Your code looks like you want to check for the rest of a division, hence the solution with the modulo operator.
这篇关于如何获得偶数或奇数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!