输出一个由*组成的三角形
时间: 2024-06-12 10:11:05 浏览: 3
以下是输出一个由*组成的三角形的代码:
```
#include <iostream>
using namespace std;
int main() {
int n;
cout << "请输入三角形的行数:";
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n - i; j++) {
cout << " ";
}
for (int k = 1; k <= 2 * i - 1; k++) {
cout << "*";
}
cout << endl;
}
return 0;
}
```
运行结果:
```
请输入三角形的行数:5
*
***
*****
*******
*********
```
相关问题
用Python输出一个用*组成的等腰三角形
好的,下面是用Python输出一个用`*`组成的等腰三角形的代码:
```python
n = int(input("请输入三角形的行数:"))
# 打印上半部分
for i in range(1, n+1, 2):
s = '*' * i
print(s.center(n, ' '))
# 打印下半部分
for i in range(n-2, 0, -2):
s = '*' * i
print(s.center(n, ' '))
```
输出结果:
```
请输入三角形的行数:7
*
***
*****
*******
*********
***********
*************
```
写一个函数输出n行由*组成的等腰三角形
好的,这是一个简单的实现:
```python
def print_triangle(n):
for i in range(n):
print(' ' * (n-i-1) + '*' * (2*i+1))
print_triangle(5) # 输出5行等腰三角形
```
输出样例:
```
*
***
*****
*******
*********
```
函数`print_triangle(n)`中,`range(n)`表示循环n次,对于每一次循环,我们需要输出一行等腰三角形。
在第`i`次循环中,我们需要输出`n-i-1`个空格和`2*i+1`个星号,其中`n-i-1`表示当前行星号左边的空格数,`2*i+1`表示当前行星号的数量。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.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)