what wrong with my code ?

surik

New member
Joined
Oct 12, 2020
Messages
1
Programming Experience
Beginner
hello everyone I don't know why my output is wrong .can you help me to fix it ? Gofile
 
In the future, please post your code here, not in some external link where the life the link may be shorter than the life of the this forum.

C#:
using System;

namespace binary
    /*
input
57
output
00111001


input
47
output
00101111
    */
{
    class DecimalToBinary
    {
        static void Main(string[] args)
        {
            Console.Write("Decimal: ");
        int  n, i;       
       int[] a = new int[10];     
       Console.Write("Enter the number to convert: ");   
       n= int.Parse(Console.ReadLine());     
       for(i=0; n>0; i++)     
        {     
         a[i]=n%2;     
         n= n/2;   
        }     
       Console.Write("Binary number= ");     
       for(i=i-1 ;i>=0 ;i--)     
       {     
        Console.Write(a[i]);     
       }         
        }
    }
}
 
What error are you getting? If you aren't getting an error, what behavior are you seeing and what behavior were you expecting to see?
 
From what I can see, the output is the correct binary value.

If the issue is that you are not seeing the leading zeroes, that's because your code doesn't print the leading zeroes. Your loop is currently just starting at the most significant bit found and working its way down. If you want leading zeros start at most significant bit of your bit buffer and then work your way down.

Or better yet, use bitwise operations to check which bits are on instead of doing repeated divisions. That way you don't even need the array.

Two things tangent to your problem:
  1. In C#,
    C#:
    int
    are 32-bit values. You seem to have hardcoded things to be just 10 bits.
  2. In C#, you could simply use Convert.ToString(n, 2).
 
Back
Top Bottom