Ada*_*eck 4 vb.net comparison integer if-statement
这可能听起来很愚蠢,但我被卡住了,我没有运气在互联网上搜索会导致这种情况发生的原因.我有一个方法,我想检查,以确保输入的两个整数都是正数:
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
Run Code Online (Sandbox Code Playgroud)
现在,如果我输入一些数字
- BothPositive(1,1)= True
- BothPositive(1,2)= False
- BothPositive(-10,10)= True
为什么是这样?比较语句中的操作顺序是什么,或者"和"试图比较的是什么?我不明白为什么这不起作用.
编辑:我理解如何解决,但我的问题是为什么会发生这种情况?我想知道是什么导致了这种情况.
在Vb.Net And表示按位运算符你在做什么,以便在这里创造的值是按位AND的num1和num2和值进行比较,以0你想要做什么是单独比较每个值对0试试以下
If (num1 > 0) AndAlso (num2 > 0) Then
Run Code Online (Sandbox Code Playgroud)
注意AndAlso这里的使用而不是普通的旧And.它AndAlso是布尔运算符与按位运算符,也是短路运算符.你应该几乎总是喜欢它And
| 归档时间: |
|
| 查看次数: |
5457 次 |
| 最近记录: |