题目:1、请写一个程序,它能够打印符合以下规则的任意行数的图形,其中输入为int型参数,代表图形行数,且该行数为大于3的奇数。
解题思路:设行数为i,则前(i+1)/2行星号的数量为2i-1,后(i-1)/2行的星号与前(i-1)/2行为对称,如果将前(i-1)/2的每行字符存入栈中,当打印后(i-1)/2行时,输出栈内容即可.
代码如下:
namespace WindowsExercise
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnPrint_Click(object sender, EventArgs e)
{
//行数
int lineNumber = -1;
try
{
lineNumber = int.Parse(textBoxLineNumber.Text.Trim());
}
catch
{
MessageBox.Show("请输入数字字符!");
}
if (lineNumber>3)
{
String sStar = "*";
String sBlank = " ";//空格
//字符串栈
Stack<string> sPrintStackS = new Stack<string>();
for (int i = 1; i <= (lineNumber - 1) / 2 + 1; i++)
{
String sPrintStar = "";//用来打印每行的"*"
String sPrintBlank = "";//用来打印每行的" "
//前i 每行*的数量
int sStarNumber = 2 * i - 1;
for (int j = 1; j <= sStarNumber; j++)
{
sPrintStar = sPrintStar + sStar;
}
//前i 每行" "的数量
int sLeftBlankNumber = (lineNumber - sStarNumber) / 2;
for (int k = 1; k <= sLeftBlankNumber; k++)
{
sPrintBlank = sPrintBlank + sBlank;
}
////打印前(lineNumber-1)/2+1行
String sPrint = sPrintBlank + sPrintStar;
listBox1.Items.Add(sPrint);
//前i-1行内容写入栈
if (i <= (lineNumber - 1) / 2)
{
sPrintStackS.Push(sPrint);
}
}
//打印后(lineNumber-1)/2行
foreach (string sPrintStack in sPrintStackS)
{
listBox1.Items.Add(sPrintStack); ;
}
}
}
private void btnClear_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
}
private void Form1_Shown(object sender, EventArgs e)
{
listBox1.Items.Add("测试题:");
listBox1.Items.Add("注意:");
listBox1.Items.Add("#:可以用任意编程语言进行开发;");
listBox1.Items.Add("1、请写一个程序,它能够打印符合以下规则的任意行数的图形,");
listBox1.Items.Add("其中输入为int型参数,代表图形行数,且该行数为大于3的奇数。");
listBox1.Items.Add("");
textBoxLineNumber.Text = "5";
btnPrint_Click(sender, e);
}
}
}
输出内容如下: