使用“And”比较整数在 If 语句中
这可能听起来很愚蠢,但我被困住了,而且我没有运气在互联网上搜索导致这种情况发生的原因。我有一个方法,我想检查以确保输入的两个整数都是正数:
Public Function BothPositive(ByVal num1 As Integer, ByVal num2 As Integer) As Boolean
If (num1 And num2) > 0 Then
Return True
Else
Return False
End If
End Function
现在,如果我要在中输入一些数字
- 两个正数(1,1) = True
- 两个正数(1,2) = False
- 两个正数(-10, 10) = True
这是为什么?比较语句中的运算顺序发生了什么或者“And”试图比较什么?我不明白为什么这行不通。
编辑:我知道如何解决,但我的问题是为什么会发生这种情况?我想知道到底发生了什么事情导致了这种情况。
This may sound dumb but I am stuck and I am having no luck searching on the internet what would be causing this to happen. I have a method that I want to check to make sure that both integers entered are both positive:
Public Function BothPositive(ByVal num1 As Integer, ByVal num2 As Integer) As Boolean
If (num1 And num2) > 0 Then
Return True
Else
Return False
End If
End Function
Now if I were to enter some numbers in
- BothPositive(1,1) = True
- BothPositive(1,2) = False
- BothPositive(-10, 10) = True
Why is this? What is going on with the order of operations in the comparison statement or what is the "And" trying to compare? I don't see why this wouldn't work.
EDIT: I understand how to work around but my question is why is this occuring? I want to know what is going on that is causing this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Vb.Net 中,
And
表示按位运算符,因此您在这里所做的是创建一个值,该值是num1
和 < 的按位AND
。 code>num2 并将该值与 0 进行比较。您想要做的是将每个值分别与 0 进行比较。请尝试以下操作 请注意此处使用
AndAlso
而不是普通的旧以及
。AndAlso
是一个布尔运算符与按位运算符,也是短路运算符。你应该几乎总是更喜欢它而不是And
In Vb.Net
And
represents a bitwise operator so what you're doing here is creating a value which is the bitwiseAND
ofnum1
andnum2
and comparing that value to 0. What you want to do is compare each value individually against 0. try the followingNote the use of
AndAlso
here instead of plain oldAnd
. TheAndAlso
is a boolean operator vs. a bitwise and is also short circuiting. You should almost always prefer it overAnd
And 是一个布尔运算,不会按照您期望的方式处理整数(它正在执行按位或)。您必须将其写为
If num1 > 0 And num2 > 0 那么
...And is a boolean operation, and won't work on integers the way you are expecting (it is doing a bitwise or). You have to write this as
If num1 >0 And num2 > 0 Then
...