0
点赞
收藏
分享

微信扫一扫

1027 打印沙漏(附详细注释,逻辑分析)


写在前面

  • 实现思路
  • 等差数列
  • 层数计算公式,满足​​2*x^2-1<n​​公式的最大正整数x
  • 当层字符个数​​2*x-1​
  • 当层空格个数​​(bottom-2*x+1)/2​
  • 编译错误
  • sqrt 函数,引入​​cmath​​函数库
  • 题目较简单,熟练情况下10分钟a题
  • 实在看不下去难理解的代码

测试用例

input:
19 *
output:
*****
***
*
***
*****
2

ac代码

#include <cmath>
#include <iostream>
using namespace std;
int main ()
{
int n, scs = 0, cs = 0, bottom = 0;
char ch;
scanf("%d %c", &n, &ch);
scs = cs = sqrt((n+1)/2);
bottom = 2*cs - 1;

for(int i=0; i<cs; i++)
{
for(int k=0; k<(bottom-(2*scs-1))/2; k++) printf(" ");
for(int j=0; j<2*scs-1; j++) printf("%c", ch);
printf("\n");
if(scs<=0) break;
scs--;
}

int xcs = 2;
for(int i=0; i<cs-1; i++)
{
for(int k=0; k<(bottom-(2*xcs-1))/2; k++) printf(" ");
for(int j=0; j<2*xcs-1; j++) printf("%c", ch);
printf("\n");
if(xcs>cs) break;
xcs++;
}
printf("%d", n-2*cs*cs+1);

return 0;
}

学习代码

  • 实现思路(不推荐)
  • 循环查找最大行数
  • 上三角输出
  • 下三角输出

#include <iostream>
using namespace std;
int main() {
int N, row = 0;
char c;
cin >> N >> c;
for (int i = 0; i < N; i++) {
if ((2 * i * (i + 2) + 1) > N) {
row = i - 1;
break;
}
}
for (int i = row; i >= 1; i--) {
for (int k = row - i; k >= 1; k--) cout << " ";
for (int j = i * 2 + 1; j >= 1; j--) cout << c;
cout << endl;
}
for (int i = 0; i < row; i++) cout << " ";
cout << c << endl;
for (int i = 1; i <= row; i++) {
for (int k = row - i; k >= 1; k--) cout << " ";
for (int j = i * 2 + 1; j >= 1; j--) cout << c;
cout << endl;
}
cout << (N - (2 * row * (row + 2) + 1));
return 0;
}


举报

相关推荐

0 条评论