1 条题解
-
0
【例38.2】 图形输出
解题思路
Z类型输出x行每行x个星号。L类型输出2x-1行,第i行距中心k,左补k空格、星号数为2(x-k)-1。
正确性说明
计算规则直接来自题目定义。按所述顺序处理时,已完成部分的结果被准确保存在累加量、计数或当前状态中;下一步只加入新增贡献。最终得到完整要求的结果。
易错点
菱形的输入x是半高含中心,不能只输出x行。
复杂度
输出规模O(x²),时间O(x²),额外空间O(x)。
参考代码(C++11)
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); char type; int x; cin >> type >> x; if (type == 'Z') { for (int i = 0; i < x; i++) cout << string(x, '*') << "\n"; } else { for (int i = 0; i < 2 * x - 1; i++) { int k = abs(i - x + 1); cout << string(k, ' ') << string(2 * (x - k) - 1, '*') << "\n"; } } return 0; }
- 1