PAT Team Practice 002

问题描述

本题要求你写个程序把给定的符号打印成沙漏的形状。例如给定17个“*”,要求按下列格式打印。

*****
 ***
  *
 ***
*****

所谓“沙漏形状”,是指每行输出奇数个符号;各行符号中心对齐;相邻两行符号数差2;符号数先从大到小顺序递减到1,再从小到大顺序递增;首尾符号数相等。

给定任意N个符号,不一定能正好组成一个沙漏。

要求打印出的沙漏能用掉尽可能多的符号。

输入格式

输入在一行给出1个正整数N(≤1000)和一个符号,中间以空格分隔。

输出格式

 首先打印出由给定符号组成的最大的沙漏形状,最后在一行中输出剩下没用掉的符号数。

代码程序

// header file source
#include <stdio.h>
#include <math.h>

// main function
int main()
{
    // variable initialize
    int n = 0;
    int cnt = 0;
    char ch = ' ';

    scanf("%d %c", &n, &ch);// input data
    /* --- --- --- --- --- --- --- --- --- ---
       cnt = sqrt((n+1)/2)
       the relationship between num and row
       num    1    7    17   31
       row    1    3    5    7
       cnt    1    2    3    4
    */
    cnt = sqrt((n+1)/2);

    /* --- --- --- --- --- --- --- --- --- ---
       circle print space and character
    */
    // output upper funnel
    for(int i=0; i<cnt; i++)
    {
        int m=2*(cnt-i) - 1;
        for(int j=0; j<i; j++)
        {
            printf(" ");
        }
        for(int k=0; k<m; k++)
        {
            printf("%c", ch);
        }
        printf("\n");
    }

    // output lower funnel
    for(int i=1; i<cnt; i++)
    {
        int m=2*(i+1) - 1;
        for(int j=(cnt-i-1); j>0; j--)
        {
            printf(" ");
        }
        for(int k=0; k<m; k++)
        {
            printf("%c", ch);
        }
        printf("\n");
    }

    // number of remaining characters
    printf("%d\n", n - (2*cnt*cnt - 1));
    return 0;
}

执行结果

输入样例

33 *

输出样例

 

*******
***** *** * *** ***** ******* 2

 

posted on 2025-02-25 13:22  roadr  阅读(5)  评论(0)    收藏  举报