这种想法应该起作用:
package sandbox;public class Sandbox{ public static void main(String[] args) { int numBuckets = 12; int numItems = 34; int itemsPerBucket = (numItems / numBuckets); int remainingItems = (numItems % numBuckets); for (int i = 1; i <= numBuckets; i++) { int extra = (i <= remainingItems) ? 1:0; System.out.println("bucket " + i + " contains " + (itemsPerBucket + extra) + " items."); } }}
此输出:
bucket 1 contains 3 items.bucket 2 contains 3 items.bucket 3 contains 3 items.bucket 4 contains 3 items.bucket 5 contains 3 items.bucket 6 contains 3 items.bucket 7 contains 3 items.bucket 8 contains 3 items.bucket 9 contains 3 items.bucket 10 contains 3 items.bucket 11 contains 2 items.bucket 12 contains 2 items.
请注意,您要做的唯一循环是谈论每个存储桶。您可以轻松地询问一个存储桶编号,看看其中有多少个项目而没有循环!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)