簡體   English   中英

似乎無法弄清楚為什么我的循環不會進展

[英]Can't seem to figure out why my loop wont progress

我似乎無法弄清楚為什么我的 for 循環不起作用。 我已經上了大約一個小時了,我最近的一次是這個。 我想知道你可以用 6、9 和 20 包購買多少個 McNugget。 我需要 dopeChecker(x) 做的就是返回一個真或假。 我還沒有實施檢查下一個號碼,因為它甚至不會發現可以購買 6 包。 我知道它在某個地方的循環中,但我就是不知道在哪里。 這是麻省理工學院開放課件問題 2 的形式。我不知道你們是否看過,但我只是讓你們知道這是我獲取信息的地方。

int x = 0, y = 0, z = 0;// These will the the pack of McNuggets that we can buy.
int testFor = 0; //This will be the number of McNuggets we are looking for.
int matches = 0; //This will be the number of consecutive matches we will be looking for.

public void dopeEquation(){

    while (matches < 6){//It's 6 Because that is the smallest order of nuggets we can buy.

        //Looking for smaller nuggets then we can buy would not make sense. 
        while (testFor < 6){
            testFor++;
        }

        if (dopeChecker(testFor)){
            matches++;

        } else{
            matches = 0;
            System.out.println(x + "," + y +"," + z +"," + testFor + "," + matches);
        }

    }
}

private boolean dopeChecker(int testFor){

    for (  x = 0 ; x*6 <= testFor;  x++){
        for ( y = 0 ; y*9 <= testFor;  y++){
            for (z = 0 ; z*20 <= testFor;){
                System.out.println(x + "," + y +"," + z +"," + testFor + "," + matches);

                if (x*6 + y*9 + z*20 == testFor){
                    matches++;
                    System.out.println("match");
                    return true;
                }else{
                    System.out.println("no match");
                }
            }
        }

    }
    return false;

}
}

z 變量始終為 0,您無需更改它。

以下是最里面的 for 循環。 我已經評論了問題出在哪里。 如您所見, z永遠不會被實現。 因此,循環永遠不會終止,因為 0 <= testFor,因為 TestFor >= 6。

        for (z = 0 ; z*20 <= testFor;/* incrementor needed here*/){
            System.out.println(x + "," + y +"," + z +"," + testFor + "," + matches);

            if (x*6 + y*9 + z*20 == testFor){
                matches++;
                System.out.println("match");
                return true;
            }else{
                System.out.println("no match");
            }
        }

您的代碼進入第一個 while 循環:

while (matches < 6){

然后使用以下代碼將 testFor 增加到 6:

 while (testFor < 6){
            testFor++;
        }

然后去dopeChecker:

 dopeChecker(int testFor)

然后進入第三個循環,對於 z:

 for (z = 0 ; z*20 <= testFor;) {
 ...
 }

z 永遠不會增加,因此您需要將其寫為:

 for (z = 0 ; z*20 <= testFor; z++){
}

暫無
暫無

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

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