Question:
why doesn't this c program work?
anonymous
2011-06-29 20:25:33 UTC
converting a binary number to a decimal
I know that I'm close. it prints the wrong number and I can't figure out why. Please, provide explanation to corrections. Thanks. (Also, please try to work with THIS program, rather than giving me something totally different.). this is an intro to programming course. I think my problem is in getting it to read the 8 digits individually from right to left.

#include
#include "conio.h"

int main()

{
double bin[8], decimal=0;
float exp=0.5;
int i=0;//define variables

printf( "type the binary number:\n");//prompt the user for binary number
scanf ("%lf", &bin[i]);

for (i=7; i>=0; i--)
{

exp*=2;//function represents powers of 2

decimal+= (bin[i] * exp);
}

printf("The decimal is %lf", decimal);//prints decimal

_getch();
return 0;
} //end this program
Three answers:
tbshmkr
2011-06-29 20:49:37 UTC
exp ALWAYS equals 1 [exp *= 2]

=

exp is never used as an exponent.
Person
2011-06-30 03:36:52 UTC
You're putting the entire number into the first element of the array. You're not putting each digit into each element of the array just by dropping it into the pointer. It's still dropping into bin[0], leaving bin[1]-bin[7] filled with zeroes. Hence, you get a ridiculously high number. You should import the binary digit as an int and use a modulus function in a for loop to peel off each digit and place it into the proper element of bin[], or just skip bin[] completely and use the modulus to peel it off and multiply by exp. There may be a better way, but that's a solution off the top of my head. As for debugging, when it doubt, print it out.



Um, tbshmkr, what are you talking about? exp*=2 means exp = exp * 2. That part is fine. It's being doubled each time, then multiplied by the binary digit at that particular position.
?
2011-06-30 03:49:48 UTC
First and foremost, forget the double - all you need is char here. You'll need to read a string that contains a binary representation of your number. Do not use scanf - it's confusing and misleading.

Use fgets() instead - see a man page for examples and explanations.

Once you have a string (say, in bin), you may use your loop to get the number, yet you have to modify it somewhat - you either should use strlen() to get the length of your binary number, or just modify the exit condition to include a check for \0.

I am tempted to give you a working example, but you might be better off trying to write it yourself first.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...