[英]Is there any way to create loops based on user input?
I wanna create all possible 5 digit numbers that can be created from the numbers (0-7).我想创建可以从数字(0-7)创建的所有可能的 5 位数字。 The code below achieves this, but is there any way to make this depend on user input?
下面的代码实现了这一点,但有没有办法让这取决于用户输入? The number of loops equals the number of digits I want and each individual loop must be:
循环数等于我想要的位数,每个单独的循环必须是:
for(1st number;condition<=last number;1st number++)
So, for five digits, I have:所以,对于五位数,我有:
for(i=0;i<8;i++){
for(j=0;j<8;j++){
for(k=0;k<8;k++){
for(m=0;m<8;m++){
for(n=0;n<8;n++){
printf("%d %d %d %d %d\n",i,j,k,m,n);
}
}
}
}
}
If you want variable numbers of loops, you generally need to use recursion.如果你想要可变数量的循环,你通常需要使用递归。 Say if you want
n
digits, with the i
th digit be in the range of a[i]
, b[i]
, then you will do the following:假设你想要
n
位,第i
位在a[i]
, b[i]
的范围内,那么你将执行以下操作:
/* whatever */
int n;
int *a,*b,*number;
void recursion(int whichdigit){
if (whichdigit==n){
/* Say you managed to output number */
return;
}
for (int i=a[whichdigit];i<=b[whichdigit];i++){
number[whichdigit]=i;
recursion(whichdigit+1);
}
return;
}
int main(){
/* Say somehow you managed to obtain n */
a=malloc(n*sizeof(int));
b=malloc(n*sizeof(int));
number=malloc(n*sizeof(int))
if (!a||!b||!number){
/* unable to allocate memory */
}
/* Say somehow you managed to read a[i],b[i] for all i in 0..n-1 */
recursion(0);
return 0;
}
Warning: if you tries to have too many digits, you will likely get a segmentation fault or stack overflow error.警告:如果您尝试使用太多数字,您可能会遇到分段错误或堆栈溢出错误。
Keep iterators in an array and increment them manually.将迭代器保存在数组中并手动递增它们。
#include <assert.h>
#include <stdio.h>
#include <string.h>
void callback(unsigned n, int i[n]) {
assert(n == 5);
printf("%d %d %d %d %d\n", i[0], i[1], i[2], i[3], i[4]);
}
void iterate(unsigned n, unsigned max, void (*callback)(unsigned n, int i[n])) {
// VLA, use *alloc in real code
int i[n];
memset(i, 0, sizeof(i));
while (1) {
for (int j = 0; j < n; ++j) {
// increment first number, from the back
++i[n - j - 1];
// if it didn't reach max, we end incrementing
if (i[n - j - 1] < max) {
break;
}
// if i[0] reached max, return
if (j == n - 1) {
return;
}
// if the number reaches max, it has to be zeroed
i[n - j - 1] = 0;
}
// call the callback
callback(n, i);
}
}
int main() {
// iterate with 5 numbers to max 8
iterate(5, 8, callback);
}
The beginning and ending of what the code prints:代码打印的开头和结尾:
0 0 0 0 0
0 0 0 0 1
...
...
7 7 7 7 6
7 7 7 7 7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.