セルフテスト-1プリント砂時計(20分)C++

6934 ワード

法則を探すようなものだ.中間層から見ると、1,3,5,7,...,2 n−1の順なので、第1層から中間層に加わる文字の個数はn^2である.では、総文字数は2 n^2−1であり、nは層数であり、1から始まる.そしてテーマで与えられたN反転層数layerを利用すればよい.layer = sqrt((N+1)/2). そして簡単です.
#include 
#include 
#include 
using namespace std;

int main()
{
    int N;
    char c;
    if(scanf("%d %c",&N,&c) == 2)
    {
        int layer = sqrt((N+1)/2);
        int firstlayer = 2*layer - 1;
        int temp = layer;//    
        while(temp >= 1)
        {
            int temp2 = (firstlayer - (temp * 2 - 1)) / 2;
	        string s1(temp2,' ');
	        string s2(2*temp-1,c);
	        cout<<s1+s2<<endl;
            temp--;
        }
        
        temp +=2;
        while(temp <= layer)
        {
            int temp2 = (firstlayer - (temp * 2 - 1)) / 2;
	        string s1(temp2,' ');
	        string s2(2*temp-1,c);
	        cout<<s1+s2<<endl;
            temp++;
        }
        
        cout<<N - 2*layer*layer + 1;
    }
    
    return 0;
}