简体   繁体   English

在 If 语句中使用“与”比较整数

[英]Comparing Integers Using “And” in If Statements

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两个正(1,1)=真
  • BothPositive(1,2) = False BothPositive(1,2) = 假
  • BothPositive(-10, 10) = True 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.我想知道这是怎么回事。

In Vb.Net And represents a bitwise operator so what you're doing here is creating a value which is the bitwise AND of num1 and num2 and comparing that value to 0. What you want to do is compare each value individually against 0. try the following在 Vb.Net 中And表示一个按位运算符,因此您在这里所做的是创建一个值,该值是num1num2的按位AND ,并将该值与 0 进行比较。您要做的是将每个值分别与 0 进行比较。尝试以下

If (num1 > 0) AndAlso (num2 > 0) Then

Note the use of AndAlso here instead of plain old And .注意这里使用AndAlso而不是普通的旧And The AndAlso is a boolean operator vs. a bitwise and is also short circuiting. AndAlso是一个 boolean 运算符,而不是按位运算符,也是短路的。 You should almost always prefer it over And你应该几乎总是更喜欢它而不是And

And is a boolean operation, and won't work on integers the way you are expecting (it is doing a bitwise or).并且是 boolean 操作,并且不会以您期望的方式处理整数(它正在执行按位或)。 You have to write this as If num1 >0 And num2 > 0 Then ...你必须把它写成If num1 >0 And num2 > 0 Then ...

Public Function BothPositive(ByVal num1 As Integer, ByVal num2 As Integer) As Boolean    
 If (num1 > 0 AND num2 > 0) Then
  Return True
 Else
  Return False
 End If
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM