简体   繁体   中英

VB Case condition is true but, action is not executed

I've write the following VB code.

Dim qu1, qu2, facroredload, bx, iterations, q3, err As Double
                
bx = 0.1
qu1 = "constant"

For iterations = 0 To 10000
    qu2 = "constant" * bx
    q3 = qu1 + qu2
    facroredload = "constant" / bx ^ 2
    err = Math.Abs(q3 - facroredload)

    Select Case err
        Case > 10
            bx += 0.1
        Case err <= 10 And err > 1
            bx = bx + 0.01
        Case err <= 1 And err > 0.1
            bx = bx + 0.001
        Case err <= 0.1 And err > 0.01
            bx = bx + 0.0001
        Case err < 0.01
            Exit For
    End Select
Next

bx value reaches 1.700000000004 (I don't know why the code adds too many decimals) and then it never changes. The For statement still exciting but, bx never goes beyond 1.7 even though Case err <= 10 And err > 1 is true.

VB's Select Case is really just a fancy if statement. How each Case gets translated to an if expression depends on the format of the case expression. There are three options:

  • A range statement, like Case 1 to 10 . This translates to If err >= 1 And err <= 10 .
  • A statement that starts with a comparison operator, such as the > that begins your first Case . When using this syntax, it just inserts your test expression before the case expression, as in If err > 10 .
  • A statement that is not a range and does not start with a comparison operator, such as your second Case . This situation is treated exactly like the case with a comparison operator, where the comparison operator is implied to be = . This means your second Case is treated as If err = (err <= 10 And err > 1) .

Once you understand this you should be able to see why your second Case statement doesn't work for you. If err is 1.7, then the second case statement boils down to If err = True , but err is not True, it is a number between 1 and 10.

To fix your code you have a couple of options. The simplest solution is this:

    Select Case err
        Case > 10
            bx += 0.1
        Case > 1
            bx = bx + 0.01
        Case > 0.1
            bx = bx + 0.001
        Case > 0.01
            bx = bx + 0.0001
        Case Else
            Exit For
    End Select

If more than one Case is satisfied, only the first satisfied clause will be executed, just like an If/ElseIf . That's why the code above works even though it only specifies the lower bound of each range. If you don't like the implied upper bound, you can add it like this: Case > 1 And err <= 10 . Personally I think it's actually clearer to leave off the upper bound of each range.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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