![]() |
| | #1 |
| Registered User Join Date: Feb 2010
Posts: 1
| Help Here is the coding: Code: #include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
int sum=0;
int power=1;
int binary;
printf("Enter a binary number:");/* user enter a binary number*/
scanf("%d",&binary);
while (binary>0)
{
sum=sum+
binary%10*power;
binary=binary/10;
power=power+2;
}
printf("The decimal equivalent: %d\n",sum);
return 0;
}
Thanks for your help
|
| lexy is offline | |
| | #2 |
| Unregistered User Join Date: Jul 2007
Posts: 981
| This is because your input buffer is an int, you should be using a string instead, and parse it.
__________________ May the Source be with you. |
| Yarin is offline | |
| | #3 |
| Registered User Join Date: Dec 2009 Location: Henderson, NV
Posts: 532
| Wow. Another way would be to read the binary number as a string, the iterating through the character array (right to left) add 1,2,4,8,16, etc to the sum then spit out the sum. But your way is probably closer to what your teacher wants. Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void)
{
int nRC = 0;
int nCurVal = 1;
int sum = 0;
char inputArray[9];
memset(inputArray,0,9);
scanf("%s", inputArray);
// now walk the array:
int nPos = strlen(inputArray)-1;
while(nPos >= 0)
{
if( inputArray[nPos] == '1')
{
sum += nCurVal;
}
--nPos;
nCurVal *= 2;
}
printf( "%s converted to decimal is %d\n", inputArray, sum);
return nRC;
}
|
| jeffcobb is offline | |
![]() |
| Thread Tools | |
| Display Modes | |
|