簡體   English   中英

修改while循環以至少執行一次

[英]Modify while loop to execute at-least once

做一些考試修訂。 一個問題是,要修改代碼,以便循環至少執行一次。

我的代碼:

int x = 0;
while (x < 10) {
   if (x % 2 != 0) {
       System.out.println(x);
   }
   x++;
}

現在我知道條件為真時while將會循環,我知道我無法刪除x ++,因為這會給我無限的零。 我想我只是刪除if語句和與之相關的括號。

你同意嗎?

int x = 0;
while (x < 10) {
    System.out.println(x);
    x++;
}

盡管此特定循環實際上至少執行了一次,甚至沒有更改,但這不是while循環的屬性。

如果不滿足while循環中的條件,則該循環將永遠不會執行。

do-while循環的工作方式幾乎相同,不同之處在於條件是在執行循環后評估的,因此,循環始終至少執行一次:

void Foo(bool someCondition)
{
    while (someCondition)
    {
        // code here is never executed if someCondition is FALSE
    }
}

另一方面:

void Foo(bool someCondition)
{
    do 
    {
        // code here is executed whatever the value of someCondition
    }
    while (someCondition) // but the loop is only executed *again* if someCondition is TRUE
}

我不同意,這將改變循環的基本目的(向stdout發送其他所有數字)。

研究轉換為do / while循環。

盡管您的解決方案在技術上已經回答了該問題,但我認為這並不是他們想要的(這並不是您的錯,在我看來,這是措辭不佳的問題)。 考慮到這是一個考試問題,我認為他們在這之后是一個do while循環。

它與while循環的工作原理相同,只不過while循環結束時檢查了while條件,這意味着它將始終至少執行一次。


例:

while(condition){
    foo();
}

這里,先檢查condition ,然后如果conditiontrue ,則執行循環,並調用foo()

而在這里:

do{
    foo();
}while(condition)

循環執行一次,調用foo() ,然后檢查condition以確定是否再次執行循環。


更多:

對於進一步的閱讀,你可能想看看還是教程whiledo whilefor循環。

int x = 0;
        while (x <10){
        System.out.println(x);
            x++;
        }

將工作

編輯:我認為其他評論也是權利,do / while循環將強制執行一次代碼

var x = 0;
do {
    if (x % 2 != 0) System.out.println(x);
    x++;
} while (x < 10);

暫無
暫無

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

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