2013-02-13 175 views
4

我在这里有一个小问题,我想画一个垂直的金字塔是这样的:绘制垂直金字塔

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

    } 

回答

3

有办法有两个循环来做到这一点,但这里是一个方式做一个,并且没有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(); 
} 
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(); 
       } 
      } 
    } 
} 
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'));