描述
用例输入 1
4
用例输出 1
d d
c c
b b
a
b b
c c
d d
【以下回答由 GPT 生成】
#include <iostream>
#include <cmath>
using namespace std;
void printPattern(int n) {
int width = 2 * n - 1;
int mid = width / 2;
for (int i = 0; i < n; i++) {
for (int j = 0; j < width; j++) {
if (j == i || j == mid || j == width - i - 1) {
cout << (char)(n - i + 96);
} else {
cout << " ";
}
}
cout << endl;
}
for (int i = n - 2; i >= 0; i--) {
for (int j = 0; j < width; j++) {
if (j == i || j == mid || j == width - i - 1) {
cout << (char)(n - i + 96);
} else {
cout << " ";
}
}
cout << endl;
}
}
int main() {
int n;
cout << "请输入一个数字: ";
cin >> n;
if (n < 1) {
cout << "输入的数字必须大于等于1" << endl;
return 0;
}
printPattern(n);
return 0;
}
运行程序时,会要求用户输入一个数字n,然后调用函数printPattern
输出相应的图案。
其中,函数printPattern
中的两个嵌套循环用于遍历二维图案的每个位置,根据位置的关系来输出字母或空格。使用cout
输出字母,使用空格代表其他位置。
该程序的时间复杂度为O(n^2),其中n为输入的数字大小。
【相关推荐】