第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

遞歸函數(shù)中的文本間距,用于打印星形圖案

遞歸函數(shù)中的文本間距,用于打印星形圖案

C#
猛跑小豬 2022-08-20 17:41:02
我正在嘗試解決遞歸的練習(xí)。這個練習(xí)是用C來解決的,但為了方便起見,我首先嘗試用C#解決它(我更習(xí)慣的地方)。它說:編寫一個程序,其中用戶必須輸入一個正數(shù)n,這是2的冪(我認(rèn)為必須排除2 ^ 0 = 1,即使它沒有澄清這一點),然后在遞歸函數(shù)的幫助下打印一個特定的模式。例如 n = 8 ,請注意中間線有 8 顆星:       * (7 spaces)      ** (6 spaces)      *  (6 spaces)    **** (4 spaces)     *   (5 spaces)    **   (4 spaces)    *    (4 spaces)******** (0 spaces)   *     (3 spaces)  **     (2 spaces)  *      (2 spaces)****     (0 spaces) *       (1 space)**       (0 spaces)*        (0 spaces)n = 4 的示例:   * (3 spaces)  ** (2 spaces)  *  (2 spaces)**** (0 spaces) *   (1 space)**   (0 spaces)*    (0 spaces)我已經(jīng)從希臘語翻譯了這個練習(xí),所以如果我的措辭有誤,我提前很抱歉。我個人已經(jīng)添加了每行必須具有的所需間距,以使您更容易。我做了什么:我發(fā)現(xiàn)了遞歸函數(shù)的結(jié)構(gòu),它是(我發(fā)布了我的程序的整個代碼):static void Main(){    int n;    do    {       n = int.Parse(Console.ReadLine());    }    while (!IsPowerOf2(n)) ;    PrintRecursive(n);}static void PrintRecursive(int stars){    if (stars > 2)    {        PrintRecursive(stars / 2);        Console.WriteLine(new string(' ',0) + new string('*', stars));        PrintRecursive(stars / 2);    }    else    {        Console.WriteLine(new string(' ', 0) + "*");        Console.WriteLine(new string(' ', 0) + "**");        Console.WriteLine(new string(' ', 0) + "*");    }}static bool IsPowerOf2(int n){    return (n != 0) && ((n & (n - 1)) == 0);}這個遞歸函數(shù)為每個可接受的n產(chǎn)生正確的恒星序列(除了1,我堅持認(rèn)為它必須被排除在外)。我沒有做什么:我真的找不到一個公式來計算每個控制臺所需的間距。WriteLine() 。為了獲得模式的完全正確的格式,我必須找到一些東西來替換 String Class I 啟動的實例中的 count 參數(shù)。
查看完整描述

1 回答

?
月關(guān)寶盒

TA貢獻(xiàn)1772條經(jīng)驗 獲得超5個贊

我想,你要找的就是這個。用你的兩個處理能力。


    static void Main(string[] args)

    {

        PrintStars(8, 0, 0);

    }


    static void PrintStars(int stars, int prefix, int suffix)

    {

        if(stars == 1)

        {

            PrintStarsToConsole(stars, prefix, suffix);

            return;

        }

        var halfStars = stars >> 1;

        PrintStars(halfStars, prefix + halfStars, suffix); // for n = 4: __**

        PrintStarsToConsole(stars, prefix, suffix);        // for n = 4: ****

        PrintStars(halfStars, prefix, suffix + halfStars); // for n = 4: **__

    }


    static void PrintStarsToConsole(int stars, int prefix, int suffix)

    {

        Console.Write(new string(' ', prefix));

        Console.Write(new string('*', stars));

        Console.Write(new string(' ', suffix));

        Console.WriteLine();

    }


查看完整回答
反對 回復(fù) 2022-08-20
  • 1 回答
  • 0 關(guān)注
  • 130 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號