C++列举出变量的所有0-1组合

来源:百度知道 编辑:UC知道 时间:2024/06/20 02:26:49
比如说有三个变量 a b c
则他们的0-1组合有8种可能
分别是:000,100,110,101,110,011,001,111
如果现在有6个变量,如何在程序中显示出这六个变量所有的0-1组合
请教高手!万分感谢!

#include<iostream>
#include<cmath>
using namespace std;

int main()
{

int n;

cout<<"输入变量总数:";
cin>>n;

for(int i=0,j;i<pow((float)2,n);i++)
{
int a=i;
for(j=0;a>0;j++)
{
cout<<a%2;
a/=2;
}
if(j!=n)
{
for(int k=0;k<n-j;k++)
cout<<'0';
}
cout<<endl;
}

return 0;
}

#include<iostream>
using namespace std;
void main()
{
int count=0;
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
for(int k=0;k<2;k++)
for(int t=0;t<2;t++)
for(int h=0;h<2;h++)
for(int g=0;g<2;g++)
{
cout<<i<<j<<k<<t<<h<<g<<" ";
count++;
if(count%5==0)//display five element every line
cout<<endl;
}
cout<&