Thread: simple but not working

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #17
    Registered User Dave++'s Avatar
    Join Date
    Jun 2007
    Location
    Where the Buffalo Roam
    Posts
    40

    Cool the math way

    Alright, thanks for the code examples above.
    I will be studying them and will use them once I know and test them better.

    Below is the hardway in that it demonstrates the math and could be extended to other bases.

    As always your comments are welcome.

    Dave++

    Code:
    #include <iostream>
    #include <stdio.h>
    #include <string>
    #include <cmath>
    #include <cstdlib>
    
    std::string DecToBin(float num)
    {
      std::string str = "";
      int i, expmax;
      double top;
      const double lg2 = log(2.0);
    
      if(num == 0) return("0");
    
      expmax = floor(log(num)/lg2);
      //  std::cout <<"expmax " << expmax << std::endl;
    
      for(i=expmax; i>=0; i--){
        top = num - pow(2.0,i);    // subtract the binary basis
        //    std::cout << num << " " << top << std::endl;
        if (top < 0){
          str = str + "0";
        }
        else {
          str = str + "1";
        num = top;
        }
      }
      return(str);
    }      
    
    int main()
    {
      int num;
      printf("Enter a whole number: ");
      scanf("&#37;i", &num);
      std::cout << DecToBin(num) << std::endl; 
      //  std::cout << log(2.0) << std::endl;
    }
    ____________
    If there are no spoons, then where did all the ice cream come from? ("7")
    Last edited by Dave++; 06-21-2007 at 07:04 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. [PAID] Very simple C script - Not working?
    By spadez in forum Projects and Job Recruitment
    Replies: 2
    Last Post: 02-12-2009, 08:00 AM
  2. Simple program not working, don't know why
    By Bakster in forum C Programming
    Replies: 11
    Last Post: 01-29-2009, 01:56 PM
  3. Replies: 3
    Last Post: 09-12-2005, 09:08 AM
  4. Replies: 5
    Last Post: 02-02-2003, 10:56 AM
  5. simple program not working
    By Unregistered in forum Windows Programming
    Replies: 2
    Last Post: 03-04-2002, 11:36 PM