在Visual Basic中显示最小值

时间:2015-03-12 15:10:09

标签: vb.net visual-studio

执行程序练习以显示前三个文本框到第四个文本框中的最小值。当我输入值并点击按钮时,第四个文本框中没有弹出结果,但Visual Studio也没有给我任何错误。我犯了什么错误?

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim First As Double = TextBox1.Text
        Dim Second As Double = TextBox2.Text
        Dim Third As Double = TextBox3.Text

        If First < Second Then
        ElseIf First < Third Then
            TextBox4.Text = First
        End If

        If Second < First Then
        ElseIf Second < Third Then
            TextBox4.Text = Second
        End If

        If Third < First Then
        ElseIf Third < Second Then
            TextBox4.Text = Third

        End If
    End Sub
End Class

2 个答案:

答案 0 :(得分:4)

不要重新发明the wheel

TextBox4.Text = Math.Min(Math.Min(First, Second), Third)

关于你的原始代码:你可能想写

If A AndAlso B Then

而不是

If A Then
    ' Do Nothing
ElseIf B Then     ' Means: If (Not A) And B
    ...

答案 1 :(得分:0)

你也可以尝试这样:

If First > Second Then
   If First > Third Then
      TextBox4.Text = First
   End If
End If

If Second > First Then
   If Second > Third Then
      TextBox4.Text = Second
   End If
End If

If Third > First Then
   If Third > Second Then
      TextBox4.Text = Third
   End If
End If

所以,公式是:

If -> condition - > statement