本题要求你写个程序把给定的符号打印成沙漏的形状。例如给定17个“*”,要求按下列格式打印
*****
***
*
***
*****
所谓“沙漏形状”,是指每行输出奇数个符号;各行符号中心对齐;相邻两行符号数差2;符号数先从大到小顺序递减到1,再从小到大顺序递增;首尾符号数相等。
给定任意N个符号,不一定能正好组成一个沙漏。要求打印出的沙漏能用掉尽可能多的符号。
输入格式:
输入在一行给出1个正整数N(≤1000)和一个符号,中间以空格分隔。
输出格式:
首先打印出由给定符号组成的最大的沙漏形状,最后在一行中输出剩下没用掉的符号数。
输入样例:
19 *
输出样例:
*****
***
*
***
*****
2
C:
#include<stdio.h>
int main()
{
int i,j=1,x=0,y=0,rest,N;
char C;
scanf("%d %c",&N,&C);
while(2*j*j-1<=N)
{
j++;
}
j--;
y=2*j-1;
rest=N-2*j*j+1;
while(y>0)
{
for(i=0;i<x;i++)
printf(" ");
for(i=0;i<y;i++)
printf("%c",C);
printf("\n");
x++;
y=y-2;
}
x--;
y=y+2;
while(x>0)
{
x--;
y=y+2;
for(i=0;i<x;i++)
printf(" ");
for(i=0;i<y;i++)
printf("%c",C);
printf("\n");
}
printf("%d",rest);
return 0;
}
C++:
#include <iostream>
using namespace std;
int main()
{
int i, j = 1, x = 0, y = 0, rest, N;
char C;
cin >> N >> C;
while (2 * j * j - 1 <= N)
{
j++;
}
j--;
y = 2 * j - 1;
rest = N - 2 * j * j + 1;
while (y > 0)
{
for (i = 0; i < x; i++)
cout << " ";
for (i = 0; i < y; i++)
cout << C;
cout << endl;
x++;
y = y - 2;
}
x--;
y = y + 2;
while (x > 0)
{
x--;
y = y + 2;
for (i = 0; i < x; i++)
cout << " ";
for (i = 0; i < y; i++)
cout << C;
cout << endl;
}
cout << rest;
return 0;
}
Java:
import java.util.Scanner;
public class Pattern {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int i, j = 1, x = 0, y = 0, rest, N;
char C;
N = scanner.nextInt();
C = scanner.next().charAt(0);
while (2 * j * j - 1 <= N) {
j++;
}
j--;
y = 2 * j - 1;
rest = N - 2 * j * j + 1;
while (y > 0) {
for (i = 0; i < x; i++)
System.out.print(" ");
for (i = 0; i < y; i++)
System.out.print(C);
System.out.println();
x++;
y = y - 2;
}
x--;
y = y + 2;
while (x > 0) {
x--;
y = y + 2;
for (i = 0; i < x; i++)
System.out.print(" ");
for (i = 0; i < y; i++)
System.out.print(C);
System.out.println();
}
System.out.print(rest);
scanner.close();
}
}
Python:
N, C = map(input().split())
N = int(N)
j = 1
x, y = 0, 0
while 2 * j * j - 1 <= N:
j += 1
j -= 1
y = 2 * j - 1
rest = N - 2 * j * j + 1
while y > 0:
print(" " * x + C * y)
x += 1
y -= 2
x -= 1
y += 2
while x > 0:
x -= 1
y += 2
print(" " * x + C * y)
print(rest)