我正在编写一个代码,该代码将乘以“x”,直到达到“y”。
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = scan.nextInt();
do {
x = (int)(x*(1.1f));
}
while(x < y);
}
在答案中,我必须获取“while”执行的次数。我不知道该怎么做。
最佳答案
一般的方法是,创建 int
类型的变量 i
,并在 while 循环 block 的末尾递增它(这实际上看起来很简单)。总的来说,我会这样做:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = scan.nextInt();
int i = 0;
do {
x = (int)(x*(1.1f));
i++;
} while (x < y);
System.out.println("Loop executed " + i + " times.");
}
如果您可以使用 for
循环,请查看以下解决问题的方法:
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = scan.nextInt();
int i = 0;
for (; x < y; i++)
x = (int)(x*(1.1f));
System.out.println("Loop executed " + i + " times.");
}
}
由于 for 循环允许每次迭代执行某些语句,因此您可以在每次循环时增加计数器变量(这可以解决某些使用 continue;
语句的情况)。
关于java - 如何打印 'while' 的执行次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52686901/