本题要求你写个程序把给定的符号打印成沙漏的形状。例如给定17个“*”,要求按下列格式打印
1*****
2 ***
3 *
4 ***
5*****
COPY
所谓“沙漏形状”,是指每行输出奇数个符号;各行符号中心对齐;相邻两行符号数差2;符号数先从大到小顺序递减到1,再从小到大顺序递增;首尾符号数相等。
给定任意N个符号,不一定能正好组成一个沙漏。要求打印出的沙漏能用掉尽可能多的符号。
输入在一行给出1个正整数N(≤1000)和一个符号,中间以空格分隔。
首先打印出由给定符号组成的最大的沙漏形状,最后在一行中输出剩下没用掉的符号数。
in
119 *
COPY
out
1*****
2 ***
3 *
4 ***
5*****
62
COPY
C#
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5namespace PrintSandglass {
6
7 class CalNum {
8
9 public int GetNum (string n, ref int r) {
10 int Num = int.Parse (n); // 字符串转化为int
11 Num--;
12 r = Num % 2;
13 Num /= 2;
14 int i;
15 for (i = 3; Num > 0; i += 2) {
16
17 Num = Num - i;
18
19 if (Num == 0) {
20
21 return i;
22
23 break;
24 }
25 }
26
27 r = (r + (Num + i - 2)) * 2;
28
29 return (i - 4);
30 }
31 public void DisplaySandglass (int i) {
32 int count = 0, t = i, tcount = 0;
33 int LastNum = i;
34 for (int j = i / 2; j > 0; j--) {
35 // for (tcount = count; tcount >= 1; tcount--) { // C#一定要括起来 哪怕只有一条语句
36 // System.Console.Write (" ");
37 //}
38 for (t = i; t >= 1; t--) {
39 System.Console.Write ("*");
40 }
41 i -= 2;
42 count++;
43 System.Console.Write ("\n");
44 for (tcount = count; tcount >= 1; tcount--) {
45 System.Console.Write (" ");
46 }
47 }
48 System.Console.Write ("*\n");
49
50 count = --count;
51 t = (i += 2);
52
53 tcount = 0;
54 for (int j = 0; j < LastNum / 2; j++) {
55 for (tcount = count; tcount >= 1; tcount--) { // C#一定要括起来 哪怕只有一条语句
56 System.Console.Write (" ");
57 }
58 for (t = i; t >= 1; t--) {
59 System.Console.Write ("*");
60 }
61 i += 2;
62 count--;
63 System.Console.Write ("\n");
64
65 }
66
67 }
68
69 }
70
71 class MainEntrance {
72 static int Main (string[] args) {
73 string n = Console.ReadLine ();
74 int r = 0;
75 CalNum c = new CalNum ();
76 int LastNum = c.GetNum (n, ref r);
77
78 c.DisplaySandglass (LastNum);
79
80 System.Console.WriteLine ("{0}", r);
81 return 0;
82 }
83 }
84}
COPY
欢迎交流. 初学C#,如有不足,欢迎指出.