2

ここで少し問題があります。次のような垂直ピラミッドを描きたいです。

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();

  }
4

3 に答える 3

3

2 つのループでこれを行う方法がありますが、if条件なしで 1 つのループで行う方法を次に示します。

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();
}
于 2013-02-13T10:14:22.977 に答える
1

このコードを使用すると便利かもしれません

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();
                }
            }
    }
}
于 2013-02-13T10:09:13.557 に答える
1

?以下は、 の代わりに1 つのループと 1 つの三項式 ( ) のみを使用する最小限の方法です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'));
于 2013-02-13T11:10:27.800 に答える