You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

十进制转二进制函数输出错误(19转成10101而非10011),如何修正?

Fixing Your VB Decimal-to-Binary Function

Got it, let's break down why your function is outputting 10101 instead of the correct 10011 for the number 19, and fix it up.

The Root Cause

The biggest issue is how you're performing division in the recursive call. In VB, the / operator does floating-point division. So when you pass an odd number like 19 into n / 2, you get 9.5. Since your function expects an Integer parameter, VB rounds this value to the nearest integer (10) instead of truncating the decimal part. That wrong starting point throws off the entire recursive sequence, leading to the incorrect binary string.

You also have a minor structural issue: your Binary function is declared as a Function but doesn't return a value—you're just printing directly inside it. Then in Main, you try to print the function's return value (which is empty, since there's no Return statement), which adds unnecessary confusion.

Fixed Version 1 (Keeping Direct Printing)

If you want to stick with the direct printing approach, switch to integer division (\) and change Binary to a Sub (since it doesn't return anything):

Sub Binary(n As Integer)
    If n = 0 Or n = 1 Then
        Console.Write(n)
    Else
        Binary(n \ 2) ' Use integer division to truncate decimals
        Console.Write(n Mod 2)
    End If
End Sub

Sub Main()
    Dim n As Integer
    Console.Write("Enter Number: ")
    n = Console.ReadLine()
    Binary(n) ' Just call the sub—no need to print its return value
    Console.ReadKey()
End Sub

Fixed Version 2 (Returning a Binary String)

For a more reusable approach, have the function return the binary string instead of printing it directly. This lets you use the result elsewhere (store it, manipulate it, etc.) instead of just outputting it immediately:

Function Binary(n As Integer) As String
    If n = 0 Then
        Return "0"
    ElseIf n = 1 Then
        Return "1"
    Else
        ' Recursively get the higher bits, then append the current bit
        Return Binary(n \ 2) & (n Mod 2).ToString()
    End If
End Sub

Sub Main()
    Dim n As Integer
    Console.Write("Enter Number: ")
    n = Console.ReadLine()
    Console.WriteLine(Binary(n))
    Console.ReadKey()
End Sub

Testing It

Both versions will correctly convert 19 to 10011. The integer division (\) is the critical fix—it ensures we always get the correct quotient when dividing by 2, which is the foundation of the decimal-to-binary algorithm.

内容的提问来源于stack exchange,提问作者Sheraz Rashid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:48:25