题目描述
输入一个奇数 n
,输出一个由 *
构成的 n
阶实心菱形。
样例
输入样例:
5
输出样例:
*
***
*****
***
*
算法1:自解
#include <iostream>
using namespace std ;
int main() {
int n ; cin >> n ;
int i = 1, num ;
// 打印上三角
for (; i <= (n+1) / 2; i ++) {
// 打印空格
num = (n+1) / 2 - i ;
while (num --) cout << " " ;
// 打印“*”
num = 2 * i - 1 ;
while (num --) cout << "*" ;
cout << endl ;
}
// 打印下三角
for (i = 1; i < (n+1) / 2; i ++) {
// 打印空格
num = i ;
while (num --) cout << " " ;
// 打印“*”
num = 2 * ((n+1) / 2 - i) - 1 ;
while (num --) cout << "*" ;
cout << endl ;
}
return 0;
}
算法2:利用曼哈顿距离 c = |x1-x2| + |y1-y2|
#include <iostream>
#include <cmath>
using namespace std ;
// ┌───┬───┬───┬───┬───┐
// │ 4 │ 3 │ 2 │ 3 │ 4 │
// ├───┼───┼───┼───┼───┤
// │ 3 │ 2 │ 1 │ 2 │ 3 │
// ├───┼───┼───┼───┼───┤
// │ 2 │ 1 │ 0 │ 1 │ 2 │
// ├───┼───┼───┼───┼───┤
// │ 3 │ 2 │ 1 │ 2 │ 3 │
// ├───┼───┼───┼───┼───┤
// │ 4 │ 3 │ 2 │ 3 │ 4 │
// └───┴───┴───┴───┴───┘
// 曼哈顿距离 c = |x1-x2| + |y1-y2|
// 本题即,将 曼哈顿距离 c <= 2 的位置都设置为“*”即可
int main() {
int n ; cin >> n ;
int sx = n / 2, sy = n / 2 ;
for (int i = 0; i < n; i ++) {
for (int j = 0; j < n; j ++) {
if (abs(sx-i) + abs(sy-j) <= n/2) cout << "*" ;
else cout << " " ;
}
cout << endl ;
}
return 0;
}
算法3:借鉴别人的做法
#include <iostream>
#include <cmath>
using namespace std ;
int main() {
int n ; cin >> n ;
int i = 1, num ;
int x = n / 2 ;
for (i = -x; i <=x; i ++) {
num = abs(i) ;
while (num --) cout << " " ;
num = n - 2 * abs(i) ;
while (num --) cout << "*" ;
cout << endl ;
}
return 0;
}