Visual Basic编写最小数字程序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Visual Basic编写最小数字程序相关的知识,希望对你有一定的参考价值。

我是visual basic的新手,我正在尝试编写一个程序来确定三个中最小的数字。每次运行程序时都不会拉出消息框。这是我到目前为止:

公共类Form1

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

    Dim TextBox1 As Integer
    Dim TextBox2 As Integer
    Dim TextBox3 As Integer

    TextBox1 = Val(TextBox1)
    TextBox2 = Val(TextBox2)
    TextBox3 = Val(TextBox3)

    If TextBox1 < TextBox2 And TextBox1 < TextBox3 Then
        MessageBox.Show(TextBox1)


    End If



End Sub
答案

你可以发布前端吗?

简而言之,您的值(TextBox1,2,3)没有任何值,因为您没有为它们指定任何值

Dim value1 as Integer = CInt(TextBox1.Text)
Dim value2 as Integer = CInt(TextBox2.Text)

我假设您在前端有文本框,您可以在其中输入数字。在代码隐藏中,您需要使用.Text属性从文本框中提取值。 CInt只是一种从字符串转换为整数的方法。

另外,我使用“AndAlso”逻辑而不是“And” - 它在性能上更好。如果第一组逻辑失败,则它不会运行第二部分,从而节省了一些性能时间。

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

    Dim value1 As Integer = CInt(TextBox1.Text)
    Dim value2 As Integer = CInt(TextBox2.Text)
    Dim value3 As Integer = CInt(TextBox3.Text)

    If value1 < value2 AndAlso value1 < value3 Then
        MessageBox.Show(value1.ToString())
    Else
        MessageBox.Show("Some output here....")
    End If



End Sub
另一答案

您还可以将.Min与数组一起使用以查找最小值。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    'Declare an array of type Integer with 3 elements
    Dim value(2) As Integer
    'A variable to hold the parsed value of TextBoxes
    Dim intVal As Integer
    If Integer.TryParse(TextBox1.Text, intVal) Then
        'Assign the parsed value to an element of the array
        value(0) = intVal
    End If
    If Integer.TryParse(TextBox2.Text, intVal) Then
        value(1) = intVal
    End If
    If Integer.TryParse(TextBox3.Text, intVal) Then
        value(2) = intVal
    End If
    'Use .Min to get the smalles value
    Dim minNumber As Integer = value.Min
    MessageBox.Show($"The smalles value is {minNumber}")
    'Or
    'in older versions of vb.net
    'MessageBox.Show(String.Format("The smallest value is {0}", minNumber))
End Sub

以上是关于Visual Basic编写最小数字程序的主要内容,如果未能解决你的问题,请参考以下文章

《逆向工程核心原理》读书笔记——第8章 Visual Basic编写的exe程序特征

乙级(Basic Level) 1013 组个最小数

PTA(Basic Level)1023.组个最小数

PAT Basic 1023 组个最小数 (20 分)

如何在 LibreOffice 中使用宏和 Visual Basic 突出显示文本

在 Visual Basic 中使用循环打印平方数