C/C++将十进制数转为二进制并输出

头文件用了C++的,也能够加上#include <stdio.h>,能够用C语言的输入输出语句。ios

 

#include <iostream>//将十进制转为二进制,并输出其中1的个数。
using namespace std;
int main()
{
int t,n,a[100];
int i,k,j;
cin>>t;
while(t--)//控制多组输入
{
i=j=0;
cin>>n;
while(n!=0)//该循环将十进制转为二进制并存入数组a
{
a[i++]=n%2;
n/=2;
}
for(k=i-1;k>=0;k--)//倒序输出二进制
{
if(k==i-1)cout<<a[k];
else cout<<" "<<a[k];
if(a[k]==1)j++;
}
cout<<endl;
cout<<j<<endl;//输出1的个数
}
return 0;
}