题目

PAT B1027 打印沙漏

code

#include <iostream>
#include <algorithm>
#include <string>
#include <cmath>
using namespace std;
int main(){
    int n,bottom;  // n为总字节数
    char a;
    scanf("%d %c",&n,&a);
    bottom=(int)sqrt(2*(n+1))-1;// 下取整
    if(bottom%2==0) bottom--;//每行的符号数不能为o偶数
    int used=(1+bottom)*((1+bottom)/2)-1;
// 倒三角
    for(int i=bottom;i>=1;i-=2){ //i为当前行要输出的字符格式
        for(int j=0;j<(bottom-i)/2;j++){ //bottom为底部最大字符数 i为当前行要输出的字符数, 差值为要输出的空格数,前部分空格和后部分空格相等所以除以2
            printf(" ");
        }
        for(int j=0;j<i;j++){//输出字符
            printf("%c",a);
        }
        printf("\n");
    }
    
    // 正三角
    for(int i=3;i<=bottom;i+=2){ //i=3!! 中间的1被a倒三角输出了
        for(int j=0;j<(bottom-i)/2;j++){ //bottom为底部最大字符数 i为当前行要输出的字符数, 差值为要输出的空格数,前部分空格和后部分空格相等所以除以2
            printf(" ");
        }
        for(int j=0;j<i;j++){//输出字符
            printf("%c",a);
        }
        printf("\n");
    }

    printf("%d\n",n-used);
    
    return 0;
}

总结

  1. PAT B1027 打印沙漏

  2. 灵魂是:别想着放在一个方形里去填充,而是按顺序输出空格+字符就可以形成这种形状

相关文章:

  • 2021-12-25
  • 2021-08-29
  • 2021-12-25
  • 2022-12-23
  • 2022-12-23
  • 2021-08-29
猜你喜欢
  • 2021-10-14
  • 2022-12-23
  • 2022-12-23
  • 2021-08-17
  • 2022-12-23
  • 2021-10-29
  • 2021-11-28
相关资源
相似解决方案