convert decimal to binary

 
  1. #include <iostream>
  2. using namespace std;
  3. void decimal_binary(int x)
  4. {
  5.     int temp=x,size=0;
  6.     while (temp)
  7.     {
  8.         size++;
  9.         temp=temp/2;
  10.     }
  11.     /*if(x<0)
  12.     { 
  13.         size=size+1;
  14.         int *array=new int [size];
  15.     }
  16.     else*/
  17.         size=size+1;
  18.         int *array=new int [size];
  19. if(x<0) array[0]=1;
  20. else array[0]=0;
  21.     for(int i=size-1;i>=1;i--)
  22.     {
  23.         if(x>=0)
  24.         { array[i]=x%2;
  25.         x=x/2;
  26.         }
  27.         else 
  28.         {   array[i]=(-x)%2;
  29.             x=x/2;
  30.         }
  31.     }
  32.     for(i=0;i<size;i++)
  33.     {
  34.         cout<<array[i];
  35.     }
  36.     cout<<"B"<<endl;
  37. }
  38. int main()
  39. {
  40.     cout<<"input number:"<<endl;
  41.     int n;
  42.     cin>>n;
  43.     decimal_binary(n);
  44.     return 0;
  45. }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章