有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Jave while循环

Java初学者。使用Zybooks。对我来说,这个软件教的不好,很模糊。 问题是:

给定正整数numInsects,编写一个while循环,在不达到200的情况下打印该数字的两倍。在每个数字后面加一个空格。循环结束后,打印一条换行符。例如:如果numInsects=16,则打印:

163264128

以下是我所拥有的:

import java.util.Scanner;

public class InsectGrowth {
   public static void main (String [] args) {
      int numInsects;
      Scanner scnr = new Scanner(System.in);
      numInsects = scnr.nextInt(); // Must be >= 1

       System.out.print(numInsects + " ");

  while (numInsects <= 100) {
     numInsects = numInsects * 2;
     System.out.print(numInsects + " ");
  }

  System.out.println();

   }
}

结果如下:它没有通过200次,只是留下了一个空白。 用16个进行测试。 你的产出 16 32 64 128 用98进行测试。 你的产出 98 196 用200个进行测试。 产出不同。见下面的亮点。 你的产出 200 预期产量


共 (4) 个答案

  1. # 1 楼答案

    将第一次打印移动到while循环中,并检查200

    public class InsectGrowth {
       public static void main (String [] args) {
          int numInsects;
          Scanner scnr = new Scanner(System.in);
          numInsects = scnr.nextInt(); // Must be >= 1
    
          while (numInsects < 200) {
              System.out.print(numInsects + " ");
             numInsects = numInsects * 2;
          }
    
          System.out.println();
    
       }
    }
    
  2. # 2 楼答案

    while循环看到的是numInsects的当前值,而不是实际应用的内容

    示例:

    import java.util.Scanner;
    
    public class ex {
    
        public static void main(String[] args) {
            int numInsects;
            Scanner scnr = new Scanner(System.in);
            numInsects = scnr.nextInt(); // Must be >= 1
    
            System.out.print(numInsects + " ");
            /*
              is  16 less than 200? yes
              is  32  less than 200? yes
              is  64 less than 200? yes
              is  128 less than 200? yes
              is  256 less than 200? no, break
    
              but if
              is  16 *2  less than 200? yes
              is  32  *2  less than 200? yes
              is  64 *2  less than 200? yes
              is  128  *2 less than 200? no, break
            */
    
            while (numInsects * 2 < 200) {
                numInsects = numInsects * 2;
                System.out.print(numInsects + " ");
            }
    
            System.out.println();
    
        }
    }
    
  3. # 3 楼答案

    这是一个处理边缘案例场景的问题。如您所见,您的while循环超过了边界条件一次迭代。所以你只需要调整条件

    用以下代码块替换while循环:

         if(numInsects <= 200) {
             System.out.print(numInsects);
         }
         while (numInsects <= 100) {
             numInsects = numInsects * 2;
             System.out.print(" " + numInsects);
         }
    
  4. # 4 楼答案

    你的numInsects总是0,你应该说int numInsects=1; 因为你正在这样做:

    0*2=0 0*2=0 0 0 0 0 0