c# - c# 使用递归打印星号金字塔
问题描述
我被问了一个问题:写一个函数,得到 n 个数字(整数),程序将打印一个星号 * 金字塔 n 数字的高度。在第一行,函数将打印一个“*”,然后下一行它将再打印 2 个 * 等等。这意味着如果我输入 4,结果需要看起来像这样,但是金字塔方式:
*
***
*****
*******
我必须以递归方式编写程序,没有任何循环..所以起初我写了这段代码,输入一个高度并将一个数字发送到一个打印模式的函数中,我知道我需要做另一个打印空格的函数但我对如何以递归方式进行理解感到困惑..
static void trianglePattern(int hight, int n)
{
if(n == 0)
{
return;
}
Console.WriteLine();
trianglePattern(hight - 1, n + 1 * 2);
}
static void Main(string[] args)
{
int hight;
Console.WriteLine("enter hight:");
hight = int.Parse(Console.ReadLine());
trianglePattern(hight, 1);
}
谢谢您的帮助
解决方案
你可以使用下面的代码它应该做你想做的事,
// function to print a row
public static void printn(int num)
{
// base case
if (num == 0)
return;
Console.Write("*");
// recursively calling printn()
printn(num - 1);
}
// function to print the pattern
public static void pattern(int n, int i)
{
// base case
if (n == 0)
return;
printn(i);
Console.WriteLine();
// recursively calling pattern()
pattern(n - 1, i + 1);
}
你的主要应该是这样的:
int n = 5; // and the could be a user input using console.readLine()
pattern(n, 1);
推荐阅读
- python - 尝试在 python 中将 Object 转换为 Float 时出错
- php - 根据输入变量构造 PHP 方法
- python - 如何使用 Scapy 生成序列号为“first:last”的数据包?
- javascript - 从 Google 表格导入数据不起作用
- python - 使用 beautifulsoup 提取 url 和 title
- pyomo - Pyomo 和 Gurobi:Pyomo 是否支持 Gurobi 的求解器回调?
- sql - Determine the Height and the Width of a BLOB
- swiftui - SwiftUI:将 ClearButton 添加到 TextField
- javascript - ES6 Class 使构造函数“+”能够被使用
- c++ - 模板实例化期间的 gcc 编译错误