P5725 【深基4.习8】求三角形

题目描述

模仿例题,打印出不同方向的正方形,然后打印三角形矩阵。中间有个空行。

输入格式

输入矩阵的规模,不超过 99

输出格式

输出矩形和正方形

输入输出样例 #1

输入 #1

1
4

输出 #1

1
2
3
4
5
6
7
8
9
01020304
05060708
09101112
13141516

01
0203
040506
07080910

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include<iostream>
using namespace std;

int main()
{
int n;
cin >> n;
int cnt = 1;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (cnt <= 9) cout << 0 << cnt;
else cout << cnt;
cnt++;
}
cout << endl;
}
cout << endl;
int count = 1;
for (int a = 1; a <= n; a++)
{
int space = 0;
while (space < 10 - 2 * (a + 1))
{
cout << " ";
space++;
}
for (int b = 1; b <= a; b++)
{
if (count <= 9) cout << 0 << count;
else cout << count;
count++;
}
cout << endl;
}
return 0;
}

但是 WA 了

经过 debug,问题出在空格的输出上。

原本计算空格的公式为10 - 2 * (a + 1),应该为(n - a) * 2才对。

修改后的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include<iostream>
using namespace std;

int main()
{
int n;
cin >> n;
int cnt = 1;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (cnt <= 9) cout << 0 << cnt;
else cout << cnt;
cnt++;
}
cout << endl;
}
cout << endl;
int count = 1;
for (int a = 1; a <= n; a++)
{
int space = 0;
while (space < (n - a) * 2)
{
cout << " ";
space++;
}
for (int b = 1; b <= a; b++)
{
if (count <= 9) cout << 0 << count;
else cout << count;
count++;
}
cout << endl;
}
return 0;
}

AC。