提问人:Another Noone 提问时间:5/6/2019 最后编辑:Another Noone 更新时间:5/6/2019 访问量:3177
在一定次数的迭代后停止循环,而不是在达到最大值时停止循环
Stop a loop after a certain amount of iterations, instead of when a max value is met
问:
爪哇岛:
我想要一个 for 循环,它不会在 i 达到某个数字时停止,而是在 x 次迭代后停止。有什么办法可以做到这一点吗?
public static int seven_sum(int num) {
int sum = 0;
for (int i = 7; i <= WHAT GOES HERE; i = i * 10 + i) {
sum = sum + i;
}
return sum;
}
答:
1赞
deHaar
5/6/2019
#1
假设你的循环中有一个特定的值求和,如果该值超过某个边界,你希望停止循环。您只需添加一个检查值的语句:if
public static void main(String args[]) {
// some value to hold a sum
int valueSum = 0;
for (int i = 0; i < 1000; i++) {
// in every iteration step, add the current value of i to valueSum
valueSum += i;
// print the current values of i and valueSum
System.out.println("Iteration no " + i + ", value sum = " + valueSum);
// stop looping if valueSum becomes 500 or greater
if (valueSum >= 500) {
break;
}
}
}
请检查控制台输出,以更好地了解循环和迭代。for
1赞
Eritrean
5/6/2019
#2
我能想到的唯一情况是:如果(迭代次数)大于(您的索引,这可能取决于一些输入值,如数组长度等)如果是这种情况,您可以将无限循环与中断语句结合起来:x
i
int iterations = 0;
for(int i = 0; true ; i++){
System.out.println("iterations count = " + ++iterations);
if(iterations == 10) break;
}
甚至不声明索引:
int iterations = 0;
for( ; ; ){
System.out.println("iterations count = " + ++iterations);
if(iterations == 10) break;
}
或者,如果您需要两个或多个自变量
int x = 10; //number of iterations wanted
for(int i = 7, j = 0; j<= x; i = i * 10 + i , j++){
// do something
}
1赞
Benjamin Urquhart
5/6/2019
#3
您可以在 for 循环中声明多个相同类型的变量:
public static int seven_sum(int num) {
int sum = 0;
for (int i = 7, iterations = 0; iterations < (number of iterations); i = i * 10 + i, iterations++) {
sum = sum + i;
}
return sum;
}
评论
i