c++ - 金字塔的递归函数
问题描述
在我的代码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");
}
解决方案
我定义了以下例程来编写一个底部长度为的金字塔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";
}
}
推荐阅读
- makefile - 我可以在生成文件中添加动态地址吗?
- arangodb - 如何替换 arangodb 中的列表元素
- java - 在命令中使用带有空格的 Runtime.exec 时“无法运行程序”
- javascript - 无法在 MacOS 上打开 Intellij
- react-native - 付款完成后获取信用卡号
- c# - 如何在运行时更改 url 徽标
- regex - 正则表达式无法对两个匹配项使用相同的字符
- html - CSS 元素出现在当前行下方。怎么修?
- xcode - 如何消除有关 MobileCoreServices 和 AssetsLibrary 的 Xcode 11.4 警告?
- php - 双击单个链接