用for循环遍历
#include
void main()
{
int a[4]={1,3,5,7};
int i,j,k,n=0;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
for(k=0;k<4;k++)
{
if(i!=j&&j!=k&&k!=i) //三个数互不相等
{
n++;
printf("[%2d] : %d%d%d\n",n,a[i],a[j],a[k]);
}
}
}
}
printf("共有%d个数\n",n);
}
一般这样的几个数或几个字母来组合,都可以先放入数组再遍历
本题刚好是1,3,5,7 是等差数列所以for(i=1;i<=7;i+=2)也可以实现
3位数?共24个整数,分别是:135.137.153.157.173.175.315.317.351.357.371.375.513.517.537.531.571.573.713.715.735.731.751.753
如果是4位数,也是24个,分别是:1357.1537.1573.1375.1753.1735.3157.3175.3517.3571.3751.3715.5137.5173.5317.5371.5713.5731.7135.7153.7351.7315.7513.7531
代码
#include
int main()
{
int i,j,k;
for(i = 1; i <=7; i += 2)
{
for(j = 1; j <=7; j += 2)
{
if(j == i) continue;
for(k = 1; k <=7; k += 2)
{
if(k == i || k == j) continue;
printf("%d%d%d\n", i,j,k);
}
}
}
return 0;
}
输出结果
135
137
153
157
173
175
315
317
351
357
371
375
513
517
531
537
571
573
713
715
731
735
751
753
思路如下:
for i in 1,3,5,7 do
for j in 3,5,7 do
for k in 5,7 do
num <- 组合(i,j,k)
if num 没有出现过
则记录
排列组合,最近正在研究.