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

时间:2015-02-12 00:20:22

标签: java algorithm loops while-loop integer

这是我到目前为止所拥有的。这个想法是它应该增加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);
 }

}

4 个答案:

答案 0 :(得分: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));
 }

答案 1 :(得分:1)

public class newClass{
public static void main(String[] args) {

    int largestValue=0;
    int n=0;

while(Math.pow(n,3)<12000) {
     if(n>largestValue)
         largestValue=n;
n++;

}
System.out.println(largestValue);


}
}

答案 2 :(得分:1)

public class Loops_13
{
   public static void main(String[] args)
   {
      int n = 0;
      while (Math.pow(n,3) < 12000)
      {
         if (Math.pow(n + 1,3) >= 12000)
            break;
         n++;
      }
      System.out.println("The largest integer n such that n^3 is less than 12,000 is " + n);
   }
}

答案 3 :(得分:1)

//Find the largest n

public class Pb5 {

    public static void main(String[] args) {
    int n=0;
     while(true) {
        if(n*n*n<12000) {
            n++;
        }
        else
            break;
      }
     System.out.println("The largest integer n less than 12000 is:: "+(n-1));
    }

}