如何使用嵌套的for循环的索引生成连续的数字列表? [英] How do I use the indices of nested for-loops to generate a consecutive list of numbers?
本文介绍了如何使用嵌套的for循环的索引生成连续的数字列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 5; k++) {
...
}
}
}
那是执行最内部代码的3 * 4 * 5 = 60次.现在,我想使用索引i,j和k的值来生成从0到59(不一定要排序)的所有数字.
That's 3 * 4 * 5 = 60 times executing the innerst code. Now I want to use the values of the indices i, j, and k to generate all numbers from 0 to 59 (not necessarily sorted).
推荐答案
好,知道了.
使k数为1,j数为k的极限,我数为j的极限乘以k的极限.
Make k count 1, j count k's limit, i count j's limit times k's limit.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 5; k++) {
int c = k * 1 + j * (5) + i * (5 * 4);
System.out.println(c);
}
}
}
输出:0..59.
这篇关于如何使用嵌套的for循环的索引生成连续的数字列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文