Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何打印次数';而';被处决了?_Java_Do While - Fatal编程技术网

Java 如何打印次数';而';被处决了?

Java 如何打印次数';而';被处决了?,java,do-while,Java,Do While,我正在写一个代码,它将乘以“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); } pub

我正在写一个代码,它将乘以“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);

    }
publicstaticvoidmain(字符串[]args){
扫描仪扫描=新扫描仪(System.in);
int x=scan.nextInt();
int y=scan.nextInt();
做{
x=(int)(x*(1.1f));
}
而(x

在回答中,我必须得到执行“while”的次数。我不知道该怎么做

一般的方法是,创建
int
类型的变量
i
,并在while循环块的末尾增加它(这个看起来很简单)。所以总的来说,我会这样做:

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循环允许每次迭代执行某些语句,因此每次循环时都可以增加计数器变量(这可以解决使用
continue;
statement的某些情况).

基本上,你需要找出
x
应该乘以
1.1
多少次才能大于
y
。或者换句话说,为了使
y/x
大于
y/x,应该将
1.1
提高到什么功率

因此,使用计数器的另一种选择是,您需要计算log1.1(y/x)并将其四舍五入到下一个
int
,在Java中,这可以通过以下方法完成:

Math.ceil (Math.log ((double)y/x) / Math.log (1.1));

您可以使用计数器变量。只需添加一个打印语句就可以了!美好的
Math.ceil (Math.log ((double)y/x) / Math.log (1.1));