首先我们都知道计算机是用二进制的形式保存数据的
那么如何用c++输出一个二进制的数呢
有以下几种方式
第一种:
#include <iostream>
using namespace std;
int main()
{
int n, i, j;
bool arr[100];
while(cin >> n)
{
i = 0;
while(n > 0)
{
arr[i] = bool(n % 2);
i++;
n /= 2;
}
for(j=i-1;j>=0;j--)
cout << arr[j];
cout << endl;
}
return 0;
}
在这里,我们需要注意到bool数组的使用 ,上述代码中有两处
对于bool(n%2),对于这个类型,bool()输出的值只有1和0
如下图
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int a[n];