-1
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int sizze(int n) //gives size of binary number 0f decimal number n.
{
    int count=0;
    while(n>1)
    {
        n=n/2;
        count++;
    }
    count =count +1;
    return count;
};
int bin(int n) //gives binary number.
{
    int l=0;
    int y[sizze(n)];
    int t=sizze(n);
    for(int i=0; i<t; i++)
    {
        y[i]=n%2;
        n=n/2;
    }
    for(int i=t-1; i>=0; i--)
    {
        l=l+y[i]*pow(10,i);
    }
    return l;
}

int main()
{
    printf("%d",bin(5));
    return 0;
}

the above code was to print binary number of a given number ,but there was some error.

I was expecting it to print 101 but it's printing 100. there was some error in l=l+y[i]*pow(10,i); but I can't understand what was wrong with it.

can anyone help me with finding the mistake.

Kalana
  • 5,631
  • 7
  • 30
  • 51

1 Answers1

2

Generally, using floating point numbers while calculation can be done using only integers is not a good idea because floating point number calculations may contain errors.
(for more information, see language agnostic - Is floating point math broken? - Stack Overflow)

In this case, you can change calculation order of additions without changing their results, so the part

    for(int i=t-1; i>=0; i--)
    {
        l=l+y[i]*pow(10,i);
    }

can be written as

    for(int i=0,delta=1; i<t; i++)
    {
        l=l+y[i]*delta;
        delta=delta*10;
    }
MikeCAT
  • 73,922
  • 11
  • 45
  • 70