第2个回答 2010-02-08
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test08 {
class Program {
static void Main(string[] args) {
Pyramid pyramid = new Pyramid(4);
Console.WriteLine(pyramid.Print());
}
}
public class Pyramid {
public int Max {
get;
private set;
}
public int Min {
get;
private set;
}
public Pyramid(int max, int min) {
if (max < min)
throw new ArgumentOutOfRangeException("max", "max must >= min.");
this.Max = max;
this.Min = min;
}
public Pyramid(int max)
: this(max, 1) {
}
public string Print() {
return Print(this.Max, this.Min);
}
public string Print(int max, int min) {
int width, height;
int left, middle, right;
int begin;
StringBuilder pyramidBuilder;
width = (max - min) * 2 + 1; //金字塔宽度
height = max - min + 1; //金字塔高度
left = middle = right = max - min; //行字符起始、中间、结束处的索引
begin = max; //行起始字符
pyramidBuilder = new StringBuilder();
//遍历行
for (int i = 0; i < height; i++, left--, right++, begin--) {
//遍历每行字符
for (int j = 0; j < width; j++) {
if (j >= left && j < middle) {
pyramidBuilder.Append(begin++);
} else if (j > middle && j <= right) {
pyramidBuilder.Append(--begin);
} else if (j == middle) {
pyramidBuilder.Append(begin = max);
} else
pyramidBuilder.Append(" ");
}
pyramidBuilder.AppendLine();
}
return pyramidBuilder.ToString();
}
}
}
第3个回答 2010-02-07
c#的控制台代码,可能并不是最好的实现
SetCursorPosition直接将光标置于所需的位置(列,行)
控制台的行号和列号都是从0开始的,列号还有上限。
static void Main(string[] args)
{
int n = Convert.ToInt32(System.Console.ReadLine());
for (int i = n; i >= 1; i--)
{
System.Console.SetCursorPosition(i - 1, n - i + 1);
for (int j = i; j <= n; j++)
{
System.Console.Write(j);
}
for (int k = n-1; k >= i && k != n; k--)
{
System.Console.Write(k);
}
System.Console.WriteLine();
}
System.Console.ReadKey();本回答被提问者采纳