绘制垂直金字塔
本文关键字:金字塔 垂直 绘制 | 更新日期: 2023-09-27 17:58:52
我有一个小问题,我想画一个垂直的金字塔,如下所示:
O
OO
OOO
OOOO
OOOOO
OOOO
OOO
OO
O
但我似乎不知道该怎么做。我得到的只是:
O
OO
OOO
OOOO
OOOOO
OOOOOO
OOOOOOO
OOOOOOOO
OOOOOOOOO
这是我的代码:
int width = 5;
for (int y = 1; y < width * 2; y++)
{
for (int x = 0; x < y; x++)
{
Console.Write("O");
}
Console.WriteLine();
}
有两种方法可以用两个循环来实现这一点,但这里有一种方法可以使用一个循环来完成,而不需要if
条件:
for (int y = 1; y < width * 2; y++)
{
int numOs = width - Math.Abs(width - y);
for (int x = 0; x < numOs; x++)
{
Console.Write("O");
}
Console.WriteLine();
}
使用此代码可能有用的
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication59
{
class Program
{
static void Main(string[] args)
{
int numberoflayer = 6, Space, Number;
Console.WriteLine("Print paramid");
for (int i = 1; i <= numberoflayer; i++) // Total number of layer for pramid
{
for (Space = 1; Space <= (numberoflayer - i); Space++) // Loop For Space
Console.Write(" ");
for (Number = 1; Number <= i; Number++) //increase the value
Console.Write(Number);
for (Number = (i - 1); Number >= 1; Number--) //decrease the value
Console.Write(Number);
Console.WriteLine();
}
}
}
}
这里有一个只有一个循环和一个三元表达式(?
)而不是if
:的最小方法
int width = 5;
for (int y = 1; y < width * 2; y++)
Console.WriteLine(String.Empty.PadLeft(y < width ? y : width * 2 - y, 'O'));
或者没有检查的版本:
for (int y = 1; y < width * 2; y++)
Console.WriteLine(String.Empty.PadLeft(Math.Abs(width * (y / width) - (y % width)), 'O'));