C++ 使用单个参数递归打印菱形

C++ 使用单个参数递归打印菱形,c++,recursion,C++,Recursion,下面的代码实现了我想要的功能,但是我需要它,这样三角形函数只接受一个参数maxrow。我认为函数可能需要从maxrow开始倒计时,直到它等于1,但是如何从菱形的中间开始打印让我感到困惑。这怎么可能呢 #include <iostream> #include <string> void print_row(unsigned int cnt) { while(cnt --> 0) std::cout << "* "; // or for loop,

下面的代码实现了我想要的功能,但是我需要它,这样三角形函数只接受一个参数maxrow。我认为函数可能需要从maxrow开始倒计时,直到它等于1,但是如何从菱形的中间开始打印让我感到困惑。这怎么可能呢

#include <iostream>
#include <string>
void print_row(unsigned int cnt)
{
     while(cnt --> 0) std::cout << "* "; // or for loop, I just think --> is cute
     std::cout << '\n';
}

void triangle(int maxrow, int row = 0)
{
     if (row >= maxrow)
     {
         print_row(row);
     }
     else
     {
         std::cout << std::string(maxrow-row, ' ');
         print_row(row);

         triangle(maxrow, row+1);

         std::cout << std::string(maxrow-row, ' ');
         print_row(row);
     }
}

int main()
{
     std::cout << "Enter total lines: ";
     int x;
     std::cin >> x;
     std::cout << '\n';
     triangle(x);
}
#包括
#包括
无效打印行(未签名整数cnt)
{
而(cnt-->0)std::cout很可爱
std::cout=maxrow)
{
打印行(行);
}
其他的
{

std::cout创建一个helper函数并调用它:

void triangle_helper(int maxrow) {
    triangle(maxrow, 0);
}
例如,您可以进一步将
triangle\u helper
重命名为
triangle
,将
triangle
重命名为
triangle\u impl
,和/或将其放在某个私有命名空间中