原题传送门:
https://www.luogu.com.cn/problem/P5725
题目描述
模仿例题,打印出不同方向的正方形,然后打印三角形矩阵。中间有个空行。
输入格式
输入矩阵的规模,不超过 9。
输出格式
输出矩形和正方形
输入输出样例
输入
4
输出
01020304
05060708
09101112
13141516
01
0203
040506
07080910
代码1(直接通过累加):
#include<iostream>
using namespace std;
int main() {
int n;
cin >> n;
//输出矩形部分
int temp = 1;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (temp < 10)
{
cout << 0 << temp;
}
else
{
cout << temp;
}
temp++;
}
cout << endl;
}
cout << endl;
//输出三角形部分
temp = 1;
for (int i = 0; i < n; i++)
{
//输出数字前的空格
for (int k = 0; k < n - i - 1; k++)
{
//注意这里空格,连续空了两格
cout << " ";
}
//输出数字
for (int j = 0; j < i + 1; j++)
{
if (temp < 10)
{
cout << 0 << temp;
}
else
{
cout << temp;
}
temp++;
}
cout << endl;
}
return 0;
}
代码2(先算出总数):
(相比代码2,复杂度降低了很多,但当n=2*10^9,会出现i超出int型范围。在洛谷中能AC的)
#include<iostream>
using namespace std;
int main() {
int n;
cin >> n;
//输出矩形部分
for (int i = 1; i <= n * n; i++)//n=2*10^9,会出现i超出int型范围
{
if (i < 10)
{
cout << 0 << i;
}
else
{
cout << i;
}
if (i % n == 0)
{
cout << endl;
}
}
cout << endl;
//输出三角形部分
int sum = 1;
for (int i = 1; i <= n; i++)
{
for (int k = 1; k <= n - i; k++)
{
//注意这里空格,连续空了两格
cout << " ";
}
//输出数字
while (sum <= i * (i + 1) / 2)
{
if (sum < 10)
{
cout << 0 << sum;
}
else
{
cout << sum;
}
sum++;
}
cout << endl;
}
return 0;
}
欢迎任何形式的转载,但请务必注明出处。
限于本人水平,如果文章和代码有表述不当之处,还请不吝赐教 。