0

What wrong with my code anyone help me plz .It's a decimal to binary conversion . According to my code , the out will be 2 for 10 , 3 for 11 but it output always add the last value at the end like for 3 it shows 1110 , add the previous output . What should I do now ? help me plz ?

#include<iostream>
#include<stdio.h>
using namespace std;

int main(){

    long int decimalNumber,quotient;

    int binaryNumber[100],i=0,j;

    printf("Enter any decimal number: ");

    //scanf_s("%ld",&decimalNumber);
    while(scanf_s("%ld",&decimalNumber)==1)
    {

            quotient = decimalNumber;

            while(quotient!=0){
             binaryNumber[i++]= quotient % 2;
             quotient = quotient / 2;
           }

           printf("Equivalent binary value of decimal number %d: ",decimalNumber);

           for(j = i -1 ;j>= 0;j--)
               printf("%d",binaryNumber[j]);
           printf("\n");
           printf("Enter any decimal number: ");
    }
    return 0;
}
1
  • 1
    Did you try to debug it? Commented Jun 14, 2013 at 11:12

1 Answer 1

5

You need to initialise i at the start of every loop

while(scanf_s("%ld",&decimalNumber)==1)
{
    i = 0;

Without this, you'll append each new number to the end of the last one, repeating until you write beyond the end of binaryNumber.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.