假设bool变量x个,x为变量。为用户输入。
如此全部的情况应该有 2^x种。
举例 当输入x=3;则有000,001,011,010,100,101,111,110.八种情况,即2^3种情况。
怎么样通过编程,输入x,然后输出全部的 情况。
如此全部的情况应该有 2^x种。
举例 当输入x=3;则有000,001,011,010,100,101,111,110.八种情况,即2^3种情况。
怎么样通过编程,输入x,然后输出全部的 情况。
解决方案
13
仅供参考:
//给定一个数组a[9]={"a","b","c","1","2","3","!","@","#"}, //要求程序启动后提示输入整数n(0<n<9),根据输入整数进行输出, //输出规则为:从一行一字符到n行n字符遍历数组中全部字符,例如: //n=1,则输出: //a,b,c,1,2,3,!,@,# //n=2.则如下输出: //a,b,c,1,2,3,!,@,# //aa,ab,ac,a1,a2,a3,a!,a@,a#,ba,bb,bc,b1,b2,b3,b!,b@,b#,ca,cb,cc,c1,c2,c3,c!,c@,c#,1a,1b,1c,11,12,13,1!,1@,1#,2a,2b,2c,21,22,23,2!,2@,2#,3a,3b,3c,31,32,33,3!,3@,3#,!a,!b,!c,!1,!2,!3,!!,!@,!#,@a,@b,@c,@1,@2,@3,@!,@@,@#,a,#b,#c,#1,#2,#3,#!,#@,## //…… #include <stdio.h> char a[9]={"a","b","c","1","2","3","!","@","#"}; char t[9]; void out(int m,int L) { int i; if (m==L) { for (i=0;i<m;i++) printf("%c",t[i]); for (i=0;i<m;i++) if ("#"!=t[i]) break; if (i<m) printf(","); return; } for (i=0;i<9;i++) { t[L]=a[i]; out(m,L+1); } } void out1_n(int n) { int m; for (m=1;m<=n;m++) { out(m,0); printf("\n"); } } int main() { int n; while (1) { printf("Input n(0<n<9):"); fflush(stdout); rewind(stdin); if (1==scanf("%d",&n)) { if (0<n && n<9) break; } } out1_n(n); return 0; } //Input n(0<n<9):1 //a,b,c,1,2,3,!,@,# // //Input n(0<n<9):2 //a,b,c,1,2,3,!,@,# //aa,ab,ac,a1,a2,a3,a!,a@,a#,ba,bb,bc,b1,b2,b3,b!,b@,b#,ca,cb,cc,c1,c2,c3,c!,c@,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#!#,#@a,#@b,#@c,#@1,#@2,#@3,#@!,#@@,#@#,##a,##b,##c,##1,##2,##3,##!,##@,### //
13
“给定一个小点的输入,完整单步跟踪(同时按Alt+7键查看Call Stack里面从上到下列出的对应从里层到外层的函数调用历史)一遍。”是理解递归函数工作原理的不二法门!
递归函数关注以下几个因素
·退出条件
·参数有哪些
·返回值是什么
·局部变量有哪些
·全局变量有哪些
·何时输出
·会不会导致堆栈溢出
递归函数关注以下几个因素
·退出条件
·参数有哪些
·返回值是什么
·局部变量有哪些
·全局变量有哪些
·何时输出
·会不会导致堆栈溢出
14
简单嵌套
int total=1; for(int i=0;i<x;i++) total=total*2; for(int i=0;i<total;i++) { int i_b=i; for(int ii=0;ii<x;ii++) { printf("%d",i_b%2); i_b=i_b/2; } printf(","); }