PTA B1027 打印沙漏

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fuckingone/article/details/82820433

 这道题感觉好难呀,看了答案一遍都做不出来><

注意:

1.根据公式计算得的x可能是偶数,这种情况下必须减1.

2.sqrt函数的参数必须是浮点数,因此要把系数2写成2.0,或者在参数内部乘以0.1

3.向下取整可以直接使用int型强制转换,也可以用math.h头文件下的floor

#include<cstdio>
#include<cmath>
using namespace std;
int main(){
  int n;
  char c;
  scanf("%d %c",&n,&c);
  int bottom=(int)sqrt(2.0*(n+1))-1;
  if(bottom%2==0)bottom-=1;
  int use=(bottom+1)*(bottom+1)/2-1;
  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",c);
    }
    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",c);
    }
    printf("\n");
  }
  printf("%d\n",n-use);
  return 0;
}

猜你喜欢

转载自blog.csdn.net/fuckingone/article/details/82820433