PAT Class B 1027 Printed Hourglass

write picture description here

By observation, it can be found that two opposite triangles are printed at this time, and the fixed point of one of the triangles is removed. The number of symbols contained in each triangle is the sum of the first n terms of an arithmetic progression.
Controlling the printed triangle needs to calculate the following data:

  • The number of rows in the triangle - number_rows
  • How many spaces to print on each line - the first line is number_rows-1 spaces, the nth line is number_rows-n spaces
  • How many symbols need to be printed in each line - can be found by the formula of the nth term of the arithmetic sequence, where n is the number of lines.

Therefore, solving all the problems is focused on how to find the number of rows of each triangle. The row number formula can be obtained by transforming the first n terms of the arithmetic difference sequence and the formula:
write picture description here

With the formula for the number of rows, the rest is to write the code. The pseudo code is as follows:

print_triangle()
{
    input num and symbol
    number_rows=(int)sqrt((num+1)/2);
    //打印尖端朝下的三角形
    for(i=number_rows-1;i>=0;i--)
    {
        for(k=0;k<number_rows-i-1;k++)
            print(space);
        for(j=0;j<1+2*i;j++)
            print(symbol);
        print(\n);
    }
    //打印尖端朝上但是不带尖端的三角形
    for(i=1;i<line;i++)
    {
        for(k=0;k<number_rows-i-1;k++)
            print(space);
        for(j=0;j<1+2*i;j++)
            print(symbol);
        print(\n);
    }
    //利用等差数列前n项和公式计算打印的符号的个数
    print(num-2*((number_rows*1)+(number_rows*(number_rows-1)))+1);
}

The C++ code is as follows

#include <iostream>
#include <stdio.h>

using namespace std;

int main()
{
    int num;
    char c;
    cin >> num >> c;
    //计算行数
    int line = sqrt((num + 1) / 2);
    //打印尖端朝下的三角形
    for (int i = line - 1; i >= 0; i--)
    {
        for (int j = 0; j < line - i - 1; j++)
            putchar(' ');
        for (int k = 0; k < 1 + 2 * i; k++)
            putchar(c);
        putchar('\n');
    }
    //打印尖端朝上的三角形
    for (int i = 1; i < line; i++)
    {
        for (int j = 0; j < line - i - 1; j++)
            putchar(' ');
        for (int k = 0; k < 1 + 2 * i; k++)
            putchar(c);
        putchar('\n');
    }
    //利用求和公式计算剩余的符号
    printf("%d", num - 2 * ((line * 1) + (line*(line - 1))) + 1);
    //system("pause");
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325340935&siteId=291194637