【问题标题】:Nested loops and inputting results into listbox嵌套循环并将结果输入到列表框中
【发布时间】:2015-03-19 20:52:32
【问题描述】:

我是 VB 新手,我需要编写一个程序,在输入框中每输入 100 个符号,就会在列表框中显示一个 @ 符号的条形图。这重复 4 次并四舍五入,这样 440 将给出 4 个 @ 符号,而 450 将给出 5 个 @ 符号。这是我检索每场比赛的出席情况的代码,我只需要帮助形成一个循环,将结果显示到名为lstChart 的列表框中。

    Private Sub btnChart_Click(sender As Object, e As EventArgs) Handles btnChart.Click
    'Retrieve attendance for game 1
    Dim strAttendance1 As Integer
    strAttendance1 = InputBox("Enter Attendance for Game #1.", "Chart Input")
    If strAttendance1 < 0 Then
        MessageBox.Show("Attendance must be greater than zero.", "Error")
    End If

    'Retrieve attendance for game 2
    Dim strAttendance2 As Integer
    strAttendance2 = InputBox("Enter Attendance for Game #2.", "Chart Input")
    If strAttendance2 < 0 Then
        MessageBox.Show("Attendance must be greater than zero.", "Error")
    End If

    'Retrieve attendance for game 3
    Dim strAttendance3 As Integer
    strAttendance3 = InputBox("Enter Attendance for Game #3.", "Chart Input")
    If strAttendance3 < 0 Then
        MessageBox.Show("Attendance must be greater than zero.", "Error")
    End If

    'Retrieve attendance for game 4
    Dim strAttendance4 As Integer
    strAttendance4 = InputBox("Enter Attendance for Game #4.", "Chart Input")
    If strAttendance4 < 0 Then
        MessageBox.Show("Attendance must be greater than zero.", "Error")
    End If

【问题讨论】:

    标签: vb.net loops listbox inputbox


    【解决方案1】:

    您可以使用String 的构造函数来重复字符x 次。唯一棘手的部分是 .NET 的默认舍入为 banker's rounding,因此如果您总是希望 .5 进行舍入,则需要具体说明:

    ' This could be simplified by using an array (or List) for the values.
    ' Also, interesting use of Hungarian notation, since these are Integers!
    For Each attendance In {strAttendance1, strAttendance2, strAttendance3, strAttendance4}
        Dim x = Math.Round(attendance / 100, MidpointRounding.AwayFromZero)
        lstChart.Items.Add(New String("@"c, x))
    Next
    

    【讨论】:

    • 我从未听说过 Banker 的舍入(尽管我熟悉根据 ASTM E-29 在实验室中使用这种类型的舍入),而且我不知道 .Net 的行为方式是这样的。谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-08-04
    • 2013-06-05
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多