Sheraz Rashid
Sheraz Rashid

Reputation: 9

logic is correct but output is not

It is a function that converts decimal into binary. It is not converting values to binary correctly. This gives 10101 for 19 instead of 10011. How can it be corrected?

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

Upvotes: 0

Views: 34

Answers (1)

Patrick
Patrick

Reputation: 368

This is something that might drive you crazy because of how small it is, but the problem is with which division operator you use.

Doing it with Binary(n / 2) treats the integer as a double and passes 9.5 to Binary, while Binary(n \ 2) is the designated integer division operator. You can read more about Arithmetic Operators on Microsoft's website.

Here's what I ran:

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

Output for 19: 10011

Upvotes: 2

Related Questions