今天第一次在线(浙大PAT)刷算法题,折腾好几个小时后,终于成功了:)
c用的少,写起来好费力,将多个*拼接,就百度好久。下面再用其他语言试试。
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> int main(){ /*PAT 00-自测1. 打印沙漏(20) *2015.4.13 *shaonian.ding *PATLink:http://www.patest.cn/contests/mooc-ds2015spring/00-%E8%87%AA%E6%B5%8B1 */ int test = 1000; char cStar = '*'; //scanf_s("%c", &cStar,1); scanf("%d %c", &test, &cStar); int temp = (test + 1) / 2; int n = (int)sqrt((double)temp); int i = n; for (i; i > 0; i--) { int numStar = 2 * (i - 1) + 1; char *star = (char *)calloc(numStar + 1, 1); char *space = (char *)calloc(n - i + 1, 1); char *lineStar = (char *)memset(star, cStar, numStar); char *lineSpace = (char *)memset(space, ' ', n - i); printf("%s%s ", space, lineStar); free(space); free(star); } int j = 2; for (j; j <= n; j++) { int numStar = 2 * (j - 1) + 1; char *star = (char *)calloc(numStar + 1, 1); char *space = (char *)calloc(n-j + 1, 1); char *lineStar = (char *)memset(star, cStar, numStar); char *lineSpace = (char *)memset(space, ' ', n - j); printf("%s%s ", space, lineStar); free(space); free(star); } printf("%d ", test - (2 * n * n - 1)); getchar(); return 0; }