它是将十进制转换为二进制的函数。它没有将值正确转换为二进制。这样10101
就等于19,而不是10011
。如何纠正?
Function Binary(n As Integer)
If n = 0 Or n = 1 Then
Console.Write(n)
Else
Binary(n / 2)
Console.Write(n Mod 2)
End If
End Function
Sub Main()
Dim n As Integer
Console.Write("Enter Number: ")
n = Console.ReadLine()
Console.Write(Binary(n))
Console.ReadKey()
End Sub
答案 0 :(得分:2)
这可能会令您发疯,因为它很小,但问题在于您使用的是除法运算符。
使用Binary(n / 2)
进行处理会将整数视为双精度并将9.5传递给Binary,而Binary(n \ 2)
是指定的整数除法运算符。您可以阅读有关算术运算符on Microsoft's website的更多信息。
这是我跑的东西
Module Module1
Function Binary(n As Integer)
If n = 0 Or n = 1 Then
Console.Write(n)
Else
Binary(n \ 2)
Console.Write(n Mod 2)
End If
End Function
Sub Main()
Dim n As Integer
Console.Write("Enter Number: ")
n = Console.ReadLine()
Console.Write(Binary(n))
Console.ReadKey()
End Sub
End Module
19的输出:10011