首页 > 解决方案 > 金字塔的递归函数

问题描述

在我的代码n中表示块数或no. of pyramids. 此代码仅打印一个 pyramid ,但我想编写一个递归函数,通过在每个连续的金字塔中添加两个元素 来打印n数量。pyramids

例如if n == 3
第一个金字塔

   1 1 1  
     1  

第二金字塔

 1 1 1 1 1  
   1 1 1  
     1   

第三金字塔

1 1 1 1 1 1 1  
  1 1 1 1 1  
    1 1 1  
      1 
#include "pch.h"
#include <iostream>
//-------------------------------------------------------Function for Pyramid---------------------------------------------------------------
int f(int n)
{
int no_rows, no_columns;

no_columns = n;
no_rows = n - 1;

//-------------------------------------------------------Loop for the Pyramid---------------------------------------------------------------
for (int i = 1; i <= no_rows; i++)
{
    for (int j = 0; j < no_columns; j++)
    {
        std::cout << "*";
    }
    std::cout << "\n";
    no_columns = no_columns - 2;

    for (int k = 0; k < i; k++)
    {
        std::cout << " ";
    }
}
if (n == 0) return -1;
return f(n);
}

int main()
{
int n;
std::cout << "Please Enter the number of Blocks: ";
std::cin >> n;
//-------------------------------------------------------Printing the n blocks---------------------------------------------------------------
std::cout << f(n) << std::endl;
std::cout << f(n + 2) << std::endl;
std::cout << f(n + 4) << std::endl;
system("pasue");
}

标签: c++arraysc++11recursionvisual-c++

解决方案


我定义了以下例程来编写一个底部长度为的金字塔bl。这对你来说很好。

演示

void writePyramid(int bl)
{        
    for (int j = bl, j_space=0; j>0; j-=2, ++j_space)
    {
        for(int k=0; k< j_space; ++k){
            std::cout << " ";
        }

        for (int l = 0; l<j; ++l){
            std::cout << "*";
        }

        std::cout << "\n";        
    }
}

推荐阅读