【问题标题】:How to find the largest integer (n), such that n^3 < 12,000, using a while loop如何使用 while 循环找到最大整数 (n),使得 n^3 < 12,000
【发布时间】:2015-02-12 00:20:22
【问题描述】:

这是我目前所拥有的。这个想法是它应该增加 n 直到 n^3 小于 12000,并在 12k 以下的最大整数处打印 n。

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);
 }

}

【问题讨论】:

  • 我建议使用n*n*n 而不是(int)(Math.pow(n,3))Math.pow 适用于浮点计算(尽管我会使用 n*n 而不是 Math.pow(n,2) 甚至用于浮点数)但它对于整数不是最理想的,除非您期望整数溢出,在这种情况下,转换回 int 是不是一个好主意。 (显然在这种情况下,整数溢出不会发生。)
  • 这个问题没有数学解决方案吗?听起来应该有。例如。只有 22 个小于 12000 的整数立方数。因此,保留所有立方体的数组,然后遍历它们检查它们是否低于您的目标,而不是每次都计算立方体。
  • 数学解决方案是:int n = (int) Math.pow(12000, 1.0/3); 但要修复循环解决方案,您需要在循环内更新 nCubed(当前始终为 0,您的循环不会终止。)

标签: java algorithm loops while-loop integer


【解决方案1】:

循环中每次都需要设置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));
 }

【讨论】:

  • 请注意,此答案正确打印 (n-1),因为您找到的 n 是第一个整数,使得 n^3 大于 12,000。
【解决方案2】:
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);


}
}

【讨论】:

  • 欢迎来到 SO:请使用 tour 并阅读 how to answer。提供额外的上下文和描述可以使答案对更广泛的受众更有用。
【解决方案3】:
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);
   }
}

【讨论】:

    【解决方案4】:
    //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));
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-20
      • 1970-01-01
      • 2022-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多