0

出力を印刷したい:1 3 5 7 9 11 13 15 17 19 21 1 3 5 7 9 11

誰かが私がロジックで犯している間違いを説明してもらえますか?

public class BadNews {

    public static final int MAX_ODD = 21;

    public static void writeOdds() {    
    // print each odd number

        for ( int count = 1; count <= (MAX_ODD - 2); count++) {
            System.out.print(count + " ");

            count = count + 2;
            
            // print the last odd number
                    System.out.print(count);
        }
    }

    public static void main(String[] args) {
        // write all odds up to 21
        writeOdds();

        // now, write all odds up to 11
        writeOdds();

    }
}
4

6 に答える 6

0

最初の問題は、カウンターを 2 回更新していることです。
次に、呼び出し時に、静的変数であるため、MAX_ODD をどのように正確に指定しますか。これを試して;

public class BadNews {

public static void writeOdds(int MAX_ODD) {    
// print each odd number

    for ( int count = 1; count <= MAX_ODD; count+=2) {

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

        // print the last odd number
        System.out.print(count);
    }
}

public static void main(String[] args) {
    // write all odds up to 21
    writeOdds(21); <-- Pass the MAX_ODD by parameter

    // now, write all odds up to 11
    writeOdds(11);

}
}
于 2013-11-15T10:20:13.480 に答える
0

あなたのコードには多くの問題があります。

  • ループ変数を 2 回更新します。

代わりに、for ステートメントで次のように 1 回更新します。

for ( int count = 1; count <= (MAX_ODD - 2); count+=2)

行を削除します

count = count + 2;
  • なぜ MAX_ODD-2 をチェックするのですか?

チェックcount <= MAX_ODD

  • ループ内に 1 つの print ステートメントが必要です。行を削除します。

    // 最後の奇数を表示

    System.out.print(カウント);

  • @Roy Dictus が示唆するように、writeOdds メソッドを変更して max_odd パラメータを受け入れるようにします。

于 2013-11-15T09:54:17.373 に答える
0

彼らは、パラメトリック メソッドを使用するのではなく、オッズを 11 に出力するために最終的な int と別のループを使用することを望んでいます。

public class BadNews {
    public static final int MAX_ODD = 21;

    public static void writeOdds() {
        // print each odd number
        for (int count = 1; count <= (MAX_ODD); count+=2) {
            System.out.print(count + " ");
        }

        // print the last odd number
    }

    public static void main(String[] args) {
        // write all odds up to 21
        writeOdds();
        System.out.println();
        // now, write all odds up to 11
        for (int count = 1; count <= 11; count+=2) {
            System.out.print(count + " ");
        }
    }
}
于 2018-04-18T19:57:35.633 に答える