如何用c#列印菱形圖案輪廓
這是實心鉆石的代碼,我想移除中間部分并保留邊緣。
由此,
對此,
public void DiamondOne()
{
int i, j, count = 1, number;
Console.Write("Enter number of rows:");
number = int.Parse(Console.ReadLine());
count = number - 1;
for (j = 1; j <= number; j )
{
for (i = 1; i <= count; i )
Console.Write(" ");
count--;
for (i = 1; i <= 2 * j - 1; i )
Console.Write("*");
Console.WriteLine();
}
count = 1;
for (j = 1; j <= number - 1; j )
{
for (i = 1; i <= count; i )
Console.Write(" ");
count ;
for (i = 1; i <= 2 * (number - j) - 1; i )
Console.Write("*");
Console.WriteLine();
}
Console.ReadLine();
}
先謝謝了
uj5u.com熱心網友回復:
我會選擇這樣的東西:
public void Diamond()
{
Console.WriteLine("Enter number of rows:");
bool isNumber = int.TryParse(Console.ReadLine(), out int rowsNr);
if (!isNumber)
{
Console.WriteLine("Not a number!");
return;
}
// print the upper half
for (int rowIndex = 0; rowIndex < rowsNr - 1; rowIndex )
{
for (int colIndex = 0; colIndex <= 2 * rowsNr; colIndex )
{
if (colIndex == Math.Abs(rowsNr - rowIndex) || colIndex == Math.Abs(rowsNr rowIndex))
{
Console.Write("*");
}
else
{
Console.Write(" ");
}
}
Console.WriteLine();
}
// print the lower half
for (int rowIndex = 1; rowIndex <= rowsNr; rowIndex )
{
for (int colIndex = 0; colIndex <= 2 * rowsNr; colIndex )
{
if (colIndex == rowIndex || colIndex == 2 * rowsNr - rowIndex)
{
Console.Write("*");
}
else
{
Console.Write(" ");
}
}
Console.WriteLine();
}
}
基本上你正在尋找 x 和 y 坐標。4 條邊中的每條邊都有自己的方程式(例如,左上角的方程式是 x == y),您可以在迭代時檢查這些方程式。我將代碼分為兩部分,一部分用于上半部分,一部分用于下半部分。它更具可讀性,你不會把太多的 if 陳述句放在一起而失去代碼的意義。
uj5u.com熱心網友回復:
這就是我想出的:
// Get the number of rows
int rows;
do
{
Console.WriteLine("Enter number of rows:");
} while (!int.TryParse(Console.ReadLine(), out rows));
// Print diamond
DiamondOne(rows, Console.Out);
// Wait for key press
Console.WriteLine("Press any key to exit");
Console.ReadKey(true);
static void DiamondOne(int rows, TextWriter output)
{
for (int currentRow = 0; currentRow < rows; currentRow )
{
OutputRow(rows, output, currentRow);
}
for (int currentRow = rows - 2; currentRow >= 0; currentRow--)
{
OutputRow(rows, output, currentRow);
}
}
static void OutputRow(int rows, TextWriter output, int currentRow)
{
int indentation = rows - currentRow - 1;
int diamondCentre = Math.Max((currentRow * 2) - 1, 0);
output.Write(new string(' ', indentation));
output.Write('*');
output.Write(new string(' ', diamondCentre));
if (currentRow != 0) output.Write('*');
output.WriteLine();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/536502.html
標籤:C#