Public paste
asedf
By: asdf | Date: Nov 25 2007 03:39 | Format: C++ | Expires: never | Size: 2.11 KB | Hits: 1197

  1. #include <iostream>
  2. #include <sstream>
  3.  
  4. using namespace std;  
  5.  
  6.  
  7. void dectobin(int num, int base);
  8. void convert(int n, int decimalnum, int base);
  9.  
  10.  
  11.  
  12. int main()
  13. {   char choice;
  14.     int decimal;
  15.     int base;
  16.     int bits;
  17.     base = 2;
  18.      
  19.     cout << "enter decimal: ";
  20.     cin >> decimal;
  21.     cout << endl;
  22.     cout<< "Decimal " << decimal << " = ";
  23.     convert(bits, decimal, base);
  24.     cout << " binary" <<endl;
  25.    
  26.     cout << "do it again? enter y or n: ";
  27.     cin >> choice;
  28.     switch (choice)
  29.     {
  30.            case 'y':
  31.                 return main();
  32.                 break;
  33.            case 'n':
  34.                 return 0;
  35.                 break;
  36.                 }
  37.  
  38.    
  39. }
  40.  
  41. void convert(int n, int decimalnum, int base)
  42. {
  43. int code= 0;    
  44. if (decimalnum > 0)
  45. {    
  46. dectobin(decimalnum, base);      
  47. }else
  48. if (decimalnum <0)
  49. {
  50. decimalnum = decimalnum * -1;
  51. dectobin(decimalnum, base);
  52. }
  53. if (decimalnum==0)
  54. {
  55.  cout << code;
  56.      
  57. }
  58. }
  59.  
  60. void dectobin(int num, int base)
  61.  
  62. {
  63.  
  64.                 string str;
  65.           stringstream out;
  66.        int i;
  67.  
  68.        /*
  69.        i = num % base;
  70.       if( num/base > 0)  
  71.       {  
  72.           string test;
  73.           string str;
  74.           stringstream out;
  75.           out << i;
  76.           str = out.str();
  77.           test = dectobin ( num/base, base );
  78.           cout << "here is hello from " << num << " and my result is: >" << test << "< !" << endl;
  79.           return test;
  80.        
  81.  
  82.            
  83.           }
  84.          if ( num/base == 0)
  85.          {
  86.                
  87.           i = num % base;
  88.           string str;
  89.           stringstream out;
  90.           out << i;
  91.           str = out.str();
  92.           return str;
  93.           }
  94. */
  95.      if (num == 0)
  96.      {
  97.        i = 0;
  98.        out << i;
  99.           str = out.str();
  100.          
  101.           cout << str;
  102.      }
  103.        
  104.  
  105.      if( num > 0)
  106.      {
  107.          
  108.          dectobin (num/base, base);
  109.          i =  num % base;
  110.  
  111.           out << i;
  112.           str = out.str();
  113.          
  114.           cout << str;
  115.          
  116.          }
  117.        
  118. }