8位不重复的数,用c语言写一个程序将这8位数的每种可能都写出来,一个结果一行。

2020-06-22 教育 51阅读
#include
int main(void){
int i1,i2,i3,i4,i5,i6,i7,i8,j;
    int a2[9],a3[8],a4[7],a5[6],a6[5],a7[4],a8[3];
    long c1=0,c2=9*9*8*7*6*5*4*3; //统计共有多少种组合
//共8级嵌套循环,每级代表一位,每位用一个数组储存可供选择的数字
    for(i1=1;i1<=9;i1++){        
        for(j=0;j<9;j++) a2[j]=j>=i1?j+1:j;        
        for(i2=0;i2<9;i2++){         
            for(j=0;j<8;j++) a3[j]=j>=i2?a2[j+1]:a2[j];             
            for(i3=0;i3<8;i3++){                 
                for(j=0;j<7;j++) a4[j]=j>=i3?a3[j+1]:a3[j];                
                for(i4=0;i4<7;i4++){                    
                    for(j=0;j<6;j++) a5[j]=j>=i4?a4[j+1]:a4[j];
                    for(i5=0;i5<6;i5++){                        
                        for(j=0;j<5;j++) a6[j]=j>=i5?a5[j+1]:a5[j];
                        for(i6=0;i6<5;i6++){                            
                            for(j=0;j<4;j++) a7[j]=j>=i6?a6[j+1]:a6[j];
                            for(i7=0;i7<4;i7++){                              
                                for(j=0;j<3;j++) a8[j]=j>=i7?a7[j+1]:a7[j];
                                for(i8=0;i8<3;i8++){                                    
                                    printf("%d%d%d%d%d%d%d%d\n",i1,a2[i2],a3[i3],a4[i4],a5[i5],a6[i6],a7[i7],a8[i8]);
                                    c1++;}}}}}}}}
    printf("total=%ld,C(1,9)*A(7,9)=%ld,total-C(1,9)*A(7,9)=%ld\n",c1,c2,c1-c2); //验证组合种数与循环次数是否相同 */
return 0;
}
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com