PAT B1027 打印沙漏(20)

思路:

  1. 使用数组保存每一行沙漏的最大符号数
  2. 输入一个正整数和一个符号
  3. 遍历数组,找到大于正整数的数组下标 j。
  4. 三角形底边的字符数为 (j - 1) * 2 - 1
  5. 打印沙漏
  6. 打印剩余字符:x - n[j - 1]

AC代码

#include <cstdio>
const int max_n = 200;
int n[max_n] = {0};
int i = 3;
void init() {
    n[1] = 1;
    n[2] = 7;
    int sum = 0;
    while(n[i-1] < 1000) {
        int j =  (i * 2 - 1) * 2;
        n[i] = n[i - 1] + j;
        i++;
    }
}
int main() {
    init();
    int x;
    char y;
    #ifdef ONLINE_JUDGE
    #else
        freopen("1.txt", "r", stdin);
    #endif // ONLINE_JUDGE
    scanf("%d %c", &x, &y); //x:正整数 y:符号
//    int i = 1;
//    while(n[i] != 0) {
//        printf("%d:---%d---
", i,n[i]);
//        ++i;
//    }
//    printf("*********%d*************
", i);
    int j = 1;
    while(n[j] <= x) {
        j++;
    }
    int bottom = (j - 1)*2-1; //三角形底边的字符数
    //int space = (bottom+1)*(bottom-1)/2-1;
//    printf("%d
", small);
    //打印沙漏
    //倒三角
//    printf("bottom: %d
", bottom);
    for(int i = bottom; i >= 1; i-=2) {
        for(int j = 0; j < (bottom - i) / 2; j++) {
            printf(" ");
        }
        for(int j = 0; j < i; j++) {
            printf("%c", y);
        }
        printf("
");

    }
    //正三角
    for(int i = 3; i <= bottom; i+=2) {
        for(int j = 0; j < (bottom - i) / 2 ; j++) {
            printf(" ");
        }
        for(int j = 0; j < i; j++) {
            printf("%c", y);
        }
        printf("
");
    }
    printf("%d
", x - n[j-1]);
    return 0;
}
原文地址:https://www.cnblogs.com/isChenJY/p/11289075.html