打印沙漏

题源

团体程序设计天梯赛
PTA 乙级

题解

稍微注意一下边界,数列求和公式对首项不适用

#include<iostream>
using namespace std;
int n,N;
char c;
int main(){
    cin >> N >> c;
    if(N==1){
        cout << c << endl;
        cout << 0 << endl;
        return 0;
    }
    for(n=0;2*n*n-1<N;n++);
    n--;
    N-=2*n*n-1;
    for(int i=0;i<n;i++){
        for(int j=0;j<i;j++)cout << " ";
        for(int j=0;j<2*(n-i)-1;j++)cout << c;
        cout << endl;
    }
    for(int i=n-2;0<=i;i--){
        for(int j=0;j<i;j++)cout << " ";
        for(int j=0;j<2*(n-i)-1;j++)cout << c;
        cout << endl;
    }
    cout << N << endl;
    return 0;
}
posted @ 2021-04-20 23:06  summeriver13  阅读(20)  评论(0)    收藏  举报