用CSharp实现在控制台打印输出杨辉三角
时间: 2024-05-12 16:17:48 浏览: 18
好的,以下是用C#实现在控制台打印输出杨辉三角的代码:
```
int rows = 10;
int[][] arr = new int[rows][];
for (int i = 0; i < rows; i++)
{
arr[i] = new int[i + 1];
arr[i][0] = 1;
for (int j = 1; j < i; j++)
{
arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
}
arr[i][i] = 1;
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < i + 1; j++)
{
Console.Write("{0} ", arr[i][j]);
}
Console.WriteLine();
}
```
希望能够对你有所帮助!
相关问题
用CSharp输出杨辉三角
好的,下面是C#代码:
```csharp
using System;
class Program
{
static void Main(string[] args)
{
int rows = 10; // 定义杨辉三角的行数
for (int i = 0; i < rows; i++)
{
int number = 1;
Console.Write(new string(' ', (rows - i - 1) * 2)); // 输出空格使数字居中对齐
for (int j = 0; j <= i; j++)
{
Console.Write("{0,2} ", number); // 输出每个数字
number = number * (i - j) / (j + 1); // 计算下一个数字
}
Console.WriteLine();
}
Console.ReadLine();
}
}
```
以上代码可以输出指定行数的杨辉三角。注意,为了使数字居中对齐,我们在输出数字之前输出一定数量的空格。
c#编写控制台应用程序,输出杨辉三角的前n行,要求从键盘输入n的值,使用交错数组实现。
以下是使用 C# 编写的控制台应用程序,输出杨辉三角的前 n 行:
```csharp
using System;
class Program
{
static void Main(string[] args)
{
Console.Write("请输入要输出的杨辉三角的行数:");
int n = int.Parse(Console.ReadLine());
int[][] triangle = new int[n][];
for (int i = 0; i < n; i++)
{
triangle[i] = new int[i + 1];
triangle[i][0] = 1;
triangle[i][i] = 1;
for (int j = 1; j < i; j++)
{
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
}
}
Console.WriteLine("杨辉三角的前 {0} 行如下:", n);
for (int i = 0; i < n; i++)
{
for (int j = 0; j <= i; j++)
{
Console.Write(triangle[i][j] + " ");
}
Console.WriteLine();
}
}
}
```
运行程序后,输入要输出的杨辉三角的行数,程序会使用交错数组实现并输出相应的杨辉三角。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)