亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將嵌套的 for 循環轉換為遞歸

如何將嵌套的 for 循環轉換為遞歸

墨色風雨 2022-01-12 17:11:23
誰能幫我將這個 for 循環轉換為遞歸方法:到目前為止,我添加了這兩種方法,但我仍然想更改第二個循環。先感謝您。       public void makeDesign1() {    int x;    for (int i = 0; i < 5; i++) // For loop is the one creating the rows    {        for (x = 4; x > i; x--) // Nested loop is the one creating the columns         {            System.out.print("*");        }        System.out.println();    }    System.out.println();}public static int makeDesign1Recur(int i) {    if (i == 0) {        return 0;    }    System.out.print("*");    return (makeDesign1Recur(i-1));}// How to convert this second loop recursive?public static void makeDesignRow(int i){   for ( int x = i; x>=0; x--){       makeDesign1Recur(x);       System.out.println("");   }}
查看完整描述

1 回答

?
慕容3067478

TA貢獻1773條經驗 獲得超3個贊

我認為第一步是makeDesign1()正確地重新定義。我們想為我們的繪圖傳遞一個尺寸。我們還想稍微改變邊界,讓大小為 1 的時候畫一顆星,而不是像原來的那樣:


public static void makeDesign(int n) 

{

    for (int i = 0; i < n; i++) // For loop is the one creating the rows

    {

        for (int x = n; x > i; x--) // Nested loop is the one creating the columns 

        {

            System.out.print("*");

        }


        System.out.println();

    }


    System.out.println();

}

下一步是讓兩個循環都倒計時到 1,以在時機成熟時簡化遞歸:


public static void makeDesign(int n) 

{

    for (int i = n; i > 0; i--) // For loop is the one creating the rows

    {

        for (int x = i; x > 0; x--) // Nested loop is the one creating the columns 

        {

            System.out.print("*");

        }


        System.out.println();

    }


    System.out.println();

}

現在我們可以簡單地將每個循環轉換成它自己的遞歸函數,一個調用另一個:


public static void makeDesign(int n) 

{

    if (n > 0)

    {

        makeDesignRow(n);

        makeDesign(n - 1);

    }

    else

    {

        System.out.println();

    }

}


public static void makeDesignRow(int x)

{

    if (x > 0)

    {

        System.out.print("*");

        makeDesignRow(x - 1);

    }

    else

    {

        System.out.println();

    }

}

輸出


傳遞makeDesign()一個 10 的參數,我們得到:


> java Main

**********

*********

********

*******

******

*****

****

***

**

*



查看完整回答
反對 回復 2022-01-12
  • 1 回答
  • 0 關注
  • 284 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號