如何使用while循环找到最大整数(n),使得n ^ 3 <12,000

0 java algorithm integer loops while-loop

这就是我到目前为止所拥有的.这个想法是它应该增加n直到n ^ 3小于12000,并打印出n低于12k的最高整数.

public static void main(String[] args) {
    int n = 0;
    int nCubed = (int) (Math.pow(n, 3));

    while (nCubed < 12000) {
        n++;
    }
    System.out.println("The highest integer below 12000 is " +n);
 }

}
Run Code Online (Sandbox Code Playgroud)

And*_*son 5

您需要在循环中每次都设置nCubed值:

public static void main(String[] args) {
    int n = 0;
    int nCubed = (int) (Math.pow(n, 3));

    while (nCubed < 12000) {
        n++;
        nCubed = (int) (Math.pow(n, 3));
    }
    System.out.println("The highest integer below 12000 is " +(n-1));
 }
Run Code Online (Sandbox Code Playgroud)