Saturday, 28 September 2013

C++ base 10 to base 2 logic error

C++ base 10 to base 2 logic error

I am doing a basic program to convert number from base 10 to base 2. I got
this code:
#include <cstdlib>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int main()
{
int num=0, coc=0, res=0, div=0;
printf ("Write a base 10 number\n");
scanf ("%d", &num);
div=num%2;
printf ("The base 2 value is:\n");
if(div==1)
{
coc=num/2;
res=num%2;
while(coc>=1)
{
printf ("%d", res);
res=coc%2;
coc=coc/2;
}
if(coc<1)
{
printf ("1");
}
}
else
{
printf ("1");
coc=num/2;
res=num%2;
while(coc>=1)
{
printf ("%d", res);
res=coc%2;
coc=coc/2;
}
}
printf ("\n");
system ("PAUSE");
return EXIT_SUCCESS;
}
Everything is good with certain numbers, but, if I try to convert the
number 11 to base 2, I get 1101, if I try 56 I get 100011... I know is a
logic problem and I am limited to basic algoritms and functions :(... any
ideas?

No comments:

Post a Comment