Home > Back-end >  If, Then and Select Case
If, Then and Select Case

Time:11-17

I'm writing VB Code and I see a question below

There are three positive integers A, B, C
If A is greater than B, C is equal to A B
If A is less than or equal to B, then C is equal to A-B.
Please use IF...Then and Select/Switch Case to write a program, both of which are used in this program, and additional variables can be added by yourself.

I would like to ask how to write this question, as far as I know, the answer just need only IF Then or Select Case can be realized?

        Dim A As Double = 3
        Dim B As Double = 2
        Dim C As Double = 1
        Dim D As Double = 0
        D = A - B
        Select Case D
            Case D > 0
                C = A   B
            Case D < 0
                C = A - B
        End Select
        If D > 0 Then
            C = A   B
        ElseIf D < 0 Then
            C = A - B
        End If

CodePudding user response:

In the real world you wouldn't need to use both an If/Then statement and a Select/Case statement. Since this appears to be homework, I believe the exercise is to see if you can use both conditional check.

I would setup two functions that accept two arguments (a and b) that return the value of c. In your first function use an If/Then and in your second function use a Select/Case.

E.g.

Private Function IfThenOption(a As Integer, b As Integer) As Integer
    Dim c As Integer
    If (a > b) Then
        c = a   b
    ElseIf (a < b) Then
        c = a - b
    Else
        c = a
    End If
    Return c
End Function

Private Function SelectCaseOption(a As Integer, b As Integer) As Integer
    Dim c As Integer
    Select Case True
        Case a > b
            c = a   b
        Case a < b
            c = a - b
        Case Else
            c = a
    End Select
    Return c
End Function

Example: https://dotnetfiddle.net/kwcyWc

  • Related