Hiếu Phan
Hiếu Phan

Reputation: 27

Conversion from decimal to binary in C

#include<stdio.h>
#include<math.h>
int main()
{
    int  n, p, s;
    printf("input n: ");
    scanf("%d", &n);
    p=0;
    while(n!=0){
        s += (n%2)*pow(10, p);
        p+=1;
        n/=2;
    }
    printf("%d", s);

}

I am newbie and i don't know why my code outputs wrong values. May you help me find the mistake in my code?

Upvotes: -1

Views: 1638

Answers (1)

Deepak Tatyaji Ahire
Deepak Tatyaji Ahire

Reputation: 5309

Just initialise variable s to 0.

Also, for a 32 bit integer, to avoid integer overflow due to pow() use the following method:

#include<stdio.h>

void decToBinary(int n) 
{ 
    // array to store binary number 
    int binaryNum[32]; 

    // counter for binary array 
    int i = 0; 
    while (n > 0) { 

        // storing remainder in binary array 
        binaryNum[i] = n % 2; 
        n = n / 2; 
        i++; 
    } 

    // printing binary array in reverse orader 
    for (int j = i - 1; j >= 0; j--) 
        printf("%d",binaryNum[j]); 
} 

// Driver program to test above function 
int main() 
{ 
    int n = 10; 
    decToBinary(n); 
    return 0; 
} 

Upvotes: 1

Related Questions