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

发布于 2024-11-19 08:48:40 字数 598 浏览 3 评论 0原文

这可能听起来很愚蠢,但我被困住了,而且我没有运气在互联网上搜索导致这种情况发生的原因。我有一个方法,我想检查以确保输入的两个整数都是正数:

    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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浮生面具三千个 2024-11-26 08:48:40

在 Vb.Net 中,And 表示按位运算符,因此您在这里所做的是创建一个值,该值是 num1 和 < 的按位 AND 。 code>num2 并将该值与 0 进行比较。您想要做的是将每个值分别与 0 进行比较。请尝试以下

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

操作 请注意此处使用 AndAlso 而不是普通的旧 以及AndAlso 是一个布尔运算符与按位运算符,也是短路运算符。你应该几乎总是更喜欢它而不是 And

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

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

Note the use of AndAlso here instead of plain old And. The AndAlso is a boolean operator vs. a bitwise and is also short circuiting. You should almost always prefer it over And

等往事风中吹 2024-11-26 08:48:40

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...

寂寞笑我太脆弱 2024-11-26 08:48:40
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
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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文