如何在Visual Basic中使用函数找到一个可被7整除的数字?

时间:2017-04-07 05:14:43

标签: vb.net

我的任务是:显示可被7整除的数字(范围10-25)。计算并显示不能被7整除的数字的平均值

所以我在Visual Basic中编写了这段代码。怎么改进?我不知道如何以其他方式显示数字14和21。

Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim counter As Byte = 0
    Dim accumulator As Short = 0
    Dim average As Single
    Dim loopcounter As Byte

    For loopcounter = 10 To 25
        If loopcounter Mod 7 <> 0 Then
            accumulator += loopcounter
            counter += 1
        Else
            Label1.Text = loopcounter & ", 14"
        End If
    Next

    average = accumulator / counter
    Label2.Text = average
End Sub
End Class

1 个答案:

答案 0 :(得分:0)

您可以将可被7整除的数字放入List(Of Integer),然后使用String.Join()将它们组合成循环结束时的字符串。

    Dim counter As Byte = 0
    Dim accumulator As Short = 0
    Dim average As Single
    Dim loopcounter As Byte
    Dim multiples As List(Of Integer) = New List(Of Integer)()  ' Declare list

    For loopcounter = 10 To 25
        If loopcounter Mod 7 <> 0 Then
            accumulator += loopcounter
            counter += 1
        Else
            multiples.Add(loopcounter)  ' Add multiple of 7 to list
        End If
    Next

    Label1.Text = String.Join(", ", multiples) ' Combine list into a comma-separated string
    average = accumulator / counter
    Label2.Text = average