2013-11-04 70 views
0

我的問題是我不能不保持邏輯做雖然不是blFound和intCounter < intPoitns.Length bacause按順序做while while循環開始執行時兩個語句都必須是true所以如果不是blFound它是這意味着它是真的,但它分配給布爾值false,所以爲什麼循環執行,並且不僅適用於blFound或也適用於intCounter。它看起來很容易,但是如果有人能用非常簡單的語言解釋它的請求,那麼我的大腦就不會在同一時間處理它。感謝您的時間!VB和一般邏輯undarstanding

這裏是例子: 假設intValidNumbers是一個整數數組。編寫在數組中搜索值爲247的代碼。如果該值爲founf,則顯示消息它位於數組中。如果未找到,則顯示一條表示如此的消息

Dim intPoitns() As Integer = {11, 42, 322, 24, 247} 
    Dim strInput As String = InputBox("Enter integer", "Data needed") 
    Dim intInput As Integer 
    Dim blFound As Boolean = False 
    Dim intCounter As Integer = 0 
    Dim intPosition As Integer 

    If Integer.TryParse(strInput, intInput) Then 
     Do While Not blFound And intCounter < intPoitns.Length 
      If intPoitns(intCounter) = intInput Then 
       blFound = True 
       intPosition = intCounter 
      End If 
      intCounter += 1 
     Loop 
    Else 
     MessageBox.Show("have to enter integer number") 
    End If 

    If blFound Then 
     lblResult.Text = ("You found" & intPosition + 1) 
    Else 
     lblResult.Text = ("not Found") 
    End If 
+0

作爲一個側面說明,這樣寫這樣的行會更清晰(對於人的可讀性 - 編譯器不關心): Do While(not blFound)and(intCounter peterG

回答

1

Ť他Not僅適用於blFound。所以認爲它是這樣的:

Do While (Not blFound) And (intCounter < intPoitns.Length) 
    If intPoitns(intCounter) = intInput Then 
     blFound = True 
     intPosition = intCounter 
    End IF 
    intCounter += 1 
Loop 

所以考慮到blFound = False我們可以看到,(Not blFound) == == (Not False)(True)

此外,如果blFound = True然後我們得到(Not blFound) == == (Not True)(False)

0

你是對的,對於do while工作,條件必須是真實的。

您有2條由And連接的條件,所以它們都必須爲真。

最初都是:爲blFound設置爲False

  1. Not blFound是真實的。
  2. intCounter < intPoitns.Length爲真如intCounter是0和intPoitns.Length是5

然後就遍歷陣列intPoitns。如果二者在do while條件變爲假循環將被停止:

  1. Not blFound可以成爲虛假如果blFound變爲真 - 這意味着你找到了你的項目。
  2. intCounter < intPoitns.Length如果intCounter變爲5就意味着你到了數組的末尾就變成了false。
0

do while循環執行,因爲這兩個條件的blFound,intCounter < intPoitns.Length屬實

blFound設置爲false開始,所以不blFound是真的

intCounter是0小於intPoitns.Length即5

如此真實和真實將執行循環