Hello, I am taking a programming class and I wrote the following program for C. I was unable to use the power function in the math library so I made my own, but it only works for converting from 0 to 1023, when I try 1024 the answer is wrong. I think it has something to do with the fact that 1024 requires 10 bits, but I dont know how that fits into the program's bug. thanks
#include %26lt;stdio.h%26gt;
#include %26lt;math.h%26gt;
int power (int , int);
main()
{ 
  int deci, resid, binary, count, multiplier;
  printf("input a number: ");
  scanf("%d", %26amp; deci);
  
  count=0;
  binary=0;
 if (deci%26gt;0)   
 {
 while (deci%26gt;0)
   {  
    resid=deci%2;
  multiplier = (power (10, count));
  binary=(resid*multiplier)+binary;
    deci=deci/2;
  count=count+1;  
   }
 }
 printf("0b%d\n", binary);
}
int power(int base, int exp)
{
 int ans;
 ans=1;
 if (exp==0)
  {
  return ans;
  }
 else 
  {
  while (exp%26gt;=1)
   {
   ans=base*ans;
   exp=exp-1;
   }
  return ans;
  }
}
I have trouble with C programming converting from decimal to binary?
.. I dont have a c complier any more so bear with me .. I'm doing this in my head.. But you are trying to take a binary number and you are representing it in a decimal form 
meaning your answer may be "1001"  = 9
but the var you are storing it into is seing 1001 = 1001
you are simply running out of space.. Convert your answer to char thus the answer = "1001\0" readable 
hope this works 
 and I didnt run you out to the wrong conculision
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment