题目描述 输入一个整数打印字符图形。 输入 一个整数(0 \lt n \lt 100<n<10)。 输出 一个字符图形。 c++
时间: 2025-03-24 14:23:29 浏览: 51
### C++ 实现根据整数输入打印字符图形
以下是基于引用内容设计的一个完整的 C++ 程序,能够满足题目需求。程序通过定义 `PrintLine()` 函数来完成每一行的输出,并支持正立金字塔和倒立金字塔两种模式。
#### 正立金字塔实现
```cpp
#include <iostream>
using namespace std;
// 定义 PrintLine 函数用于输出一行的内容
void PrintLine(int spaces, int m) {
for (int i = 0; i < spaces; ++i) { // 输出空格部分
cout << ' ';
}
for (int i = 1; i <= m * 2 - 1; ++i) { // 输出星号部分
cout << '*';
}
cout << endl;
}
int main() {
int n;
cin >> n; // 输入层数 n
for (int i = 1; i <= n; ++i) {
int spaces = n - i; // 计算每层前导空格数量
int maxNum = i; // 当前行的最大数字对应当前层数
PrintLine(spaces, maxNum); // 调用函数输出该行
}
return 0;
}
```
上述代码实现了正立金字塔的功能[^1]。`PrintLine()` 函数负责处理每行的输出逻辑,其中参数 `spaces` 表示每行前面的空白字符数目,而 `m` 则表示当前行中最大数值对应的星号宽度。
---
#### 倒立金字塔实现
对于倒立金字塔的需求,则可以通过调整循环条件以及计算方式轻松扩展:
```cpp
#include <iostream>
using namespace std;
// 定义 PrintLine 函数用于输出一行的内容
void PrintLine(int spaces, int m) {
for (int i = 0; i < spaces; ++i) { // 输出空格部分
cout << ' ';
}
for (int i = 1; i <= m * 2 - 1; ++i) { // 输出星号部分
cout << '*';
}
cout << endl;
}
int main() {
int n;
cin >> n; // 输入层数 n
for (int i = n; i >= 1; --i) {
int spaces = n - i; // 计算每层前导空格数量
int maxNum = i; // 当前行的最大数字对应当前层数
PrintLine(spaces, maxNum); // 调用函数输出该行
}
return 0;
}
```
此版本修改了外层循环的方向,使得图案呈现为倒立形式[^2]。
---
#### 综合版:可选正立或倒立金字塔
如果希望提供更灵活的选择功能,可以进一步改进代码结构如下所示:
```cpp
#include <iostream>
using namespace std;
// 定义 PrintLine 函数用于输出一行的内容
void PrintLine(int spaces, int m) {
for (int i = 0; i < spaces; ++i) { // 输出空格部分
cout << ' ';
}
for (int i = 1; i <= m * 2 - 1; ++i) { // 输出星号部分
cout << '*';
}
cout << endl;
}
int main() {
int n, type;
cout << "请输入层数 n 和类型(1: 正立, 2: 倒立):" << endl;
cin >> n >> type;
if (type == 1) { // 正立金字塔
for (int i = 1; i <= n; ++i) {
int spaces = n - i;
int maxNum = i;
PrintLine(spaces, maxNum);
}
} else if (type == 2) { // 倒立金字塔
for (int i = n; i >= 1; --i) {
int spaces = n - i;
int maxNum = i;
PrintLine(spaces, maxNum);
}
} else {
cout << "错误的选项!" << endl;
}
return 0;
}
```
这段综合代码允许用户选择生成正立还是倒立的金字塔形状[^3]。
---
###
阅读全文
相关推荐

















