<問題>
輸入一奇數(1~101的數字), 然後列印出星星
<解答>
這裡使用 C# 撰寫 ConsoleApplication ... 如下:
<參攷>
C# 打印空心、实心菱形
<ps.>
解題的訣竅在於利用迴圈、變數遞增、遞減及算術公式的特性來將星星的位置及列印顯示符號或空白...前題是要先解開星星之間0與1的關係!!
輸入一奇數(1~101的數字), 然後列印出星星
<解答>
這裡使用 C# 撰寫 ConsoleApplication ... 如下:
using System;
namespace ConsoleApp1
{
///
/// Program 的摘要说明
///
class Program
{
public static int number;
public static string str;
public static int i, j, k;
///
/// 應用程式的主入口點
///
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此處添加程式碼以啟動應用程式
//
Console.Write("請輸入 1 到 101 的數字: ");
str = Console.ReadLine();
CheckNumber();
Console.WriteLine();
PrintSolidRhombus();
Console.WriteLine();
PrintHollowRhombus();
Console.WriteLine();
PrintHourGlass();
Console.ReadLine();
}
///
/// to check if string is a number or not
///
private static void CheckNumber()
{
if (int.TryParse(str, out number))
{
//is a number
//to check if number is even
if (number % 2 == 0)
Environment.Exit(-1);
//to check the number scope
if (number < 1 || number > 102)
Environment.Exit(-2);
}
else
{
//not a number
Environment.Exit(-3);
}
}
///
/// to write the parameter
///
private static void WriteParam()
{
//Console.Write("\ti={0} j={1} k={2}", i, j, k);
Console.WriteLine();
}
///
/// 印空心菱形
///
public static void PrintHollowRhombus()
{
for(i = 1; i <= number; i++)
{
for(j = number; j > i; j--)
Console.Write(" ");
for(k = 1; k < 2 * i; k++)
{
if(k == 1 || k == 2 * i - 1)
Console.Write("*");
else
Console.Write(" ");
}
WriteParam();
}
for(i = 0; i < number - 1; i++)
{
for(j = 0; j <= i; j++)
Console.Write(" ");
for(k = 1; k < 2 * (number - 1) - 2 * i; k++)
{
if(k == 1 || k == (2 * (number - 1) - 2 * i - 1))
Console.Write("*");
else
Console.Write(" ");
}
WriteParam();
}
}
///
/// 印實心菱形
///
public static void PrintSolidRhombus()
{
for(i = 1; i <= number; i++)
{
for(j = number; j > i; j--)
Console.Write(" ");
for(k = 1; k < 2 * i; k++)
Console.Write("*");
WriteParam();
}
for(i = 0; i < number - 1; i++)
{
for(j = 0; j <= i; j++)
Console.Write(" ");
for(k = 1; k < 2 * (number - 1) - 2 * i; k++)
Console.Write("*");
WriteParam();
}
}
///
/// 印實心沙漏
///
public static void PrintHourGlass()
{
for (i = 0; i < number - 1; i++)
{
for (j = 1; j <= i; j++)
Console.Write(" ");
for (k = 0; k <= 2 * (number - 1) - 2 * i; k++)
Console.Write("*");
WriteParam();
}
for (i = 1; i <= number; i++)
{
for (j = number; j > i; j--)
Console.Write(" ");
for (k = 1; k < 2 * i; k++)
Console.Write("*");
WriteParam();
}
}
}
}
<參攷>
C# 打印空心、实心菱形
<ps.>
解題的訣竅在於利用迴圈、變數遞增、遞減及算術公式的特性來將星星的位置及列印顯示符號或空白...前題是要先解開星星之間0與1的關係!!
留言