1 条题解
-
0
【深基4.例6】数字直角三角形
解题思路
第 i 行输出 n-i+1 个数,数字用连续递增的计数器生成,每个数宽度为 2、不足补零。
正确性说明
各行数量依次为 n,n-1,…,1,正好形成指定方向的直角三角形;计数器保证从 1 连续排列。
易错点
数字之间没有空格;setw 仅作用于下一次输出,每个数都要设置。
复杂度
时间 O(n²),额外空间 O(1)。
参考代码(C++11)
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, k = 1; cin >> n; cout << setfill('0'); for (int i = 0; i < n; i++) { for (int j = 0; j < n - i; j++) cout << setw(2) << k++; cout << "\n"; } return 0; }
- 1