Visual Basic - 检查数字是否为二进制的函数

时间:2015-07-28 09:58:38

标签: vb.net

我代码新手,我坚持使用此代码。似乎我总是得到True作为这个功能的回应。我做错了什么?

    Private Function binary() As Boolean
    Dim number, temp As Integer
    Dim status As Boolean
    TextBox1.Text = number
    status = True

    While (True)
        If (number = 0) Then
            Exit While
        Else
            temp = number Mod 10
            If (temp > 1) Then
                status = False
                Exit While
            End If
            number = number / 10
        End If
    End While

    Return status

End Function

1 个答案:

答案 0 :(得分:2)

你的作业有错误的方法:

TextBox1.Text = number

这样,number将始终为0,即其初始值,因此每次都会立即退出While循环。它应该是:

number = Convert.ToInt32(TextBox1.Text)

或者更好的是,将其作为参数传递给函数:

Private Function binary(number as Integer) As Boolean
    Dim temp As Integer
    Dim status As Boolean

    status = True

    While (True)
        If (number = 0) Then
            Exit While
        Else
            temp = number Mod 10
            If (temp > 1) Then
                status = False
                Exit While
            End If
            number = number / 10
        End If
    End While

    Return status
End Function

然后:

Dim isBinary as Boolean
isBinary = binary(Convert.ToInt32(TextBox1.Text))