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. }
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值