簡體   English   中英

我怎樣才能讓我的while循環只打印偶數? Java Eclipse 集成開發環境

[英]How can I make it so my while-loop only prints even numbers? Java Eclipse IDE

初學者在這里。 對於我的編碼課程,我們有一個作業要求我們打印數字 1-20,但將其配置為僅輸出偶數。 這是我到目前為止所擁有的,但我很困惑。 他說要放置一個 if 語句並使用“%”運算符,但我不知道將它們放在哪里。

    int counter = 1;
    System.out.println("Part 2 - Even Numbers");
    while (counter <= 20)
    {
        //if (counter 
        System.out.printf("%d ", counter);
        counter++;
    } // end while loop

分配說明

我的輸出

正確的輸出

  if(counter % 2 == 0){
      System.out.printf("%d ", counter);
  }
  counter++;

%運算符是 mod 運算符,計數器 % 2 == 0計數器是偶數

使用fori

 public static void main(String[] args) {
        for (int i = 1; i <= 20; i++) {
            if (i % 2 == 0) {
                System.out.println(i);
            }
        }
    }

% 是余數運算

%是算術運算符,稱為MODULO 模運算符返回 2 個數字的余數。 在這種情況下,我們使用模數來確定一個數是偶數還是奇數。

奇數%2返回1

even%2返回0

while 循環遍歷前 20 個元素。 所以我們在打印元素之前放置了一個 if 語句。 如果計數器是偶數,即 (counter%2 == 0) 我們打印它。

這是打印偶數的代碼:

        int counter = 0;
        System.out.println("Part 2 - Even Numbers");
        while (counter <= 20)
        {
            if (counter%2 == 0){
                System.out.printf("%d ", counter);
            }
            counter++;
        } // end while loop

這也可以在不使用 MODULO 運算符的情況下完成:

        int counter = 0;
        System.out.println("Part 2 - Even Numbers");
        while (counter <= 20)
        {
            System.out.printf("%d ", counter);
            counter+=2;
        } // end while loop

哇!

保持學習!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM