首页 > 其他 > 详细

PAT B1027 打印沙漏(20)

时间:2019-08-02 16:10:09      阅读:92      评论:0      收藏:0      [点我收藏+]

思路:

  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---\n", i,n[i]);
//        ++i;
//    }
//    printf("*********%d*************\n", 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\n", small);
    //打印沙漏
    //倒三角
//    printf("bottom: %d\n", 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("\n");

    }
    //正三角
    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("\n");
    }
    printf("%d\n", x - n[j-1]);
    return 0;
}

PAT B1027 打印沙漏(20)

原文:https://www.cnblogs.com/isChenJY/p/11289075.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!