杨辉三角如何对齐成下图(下面代码给对歪了):
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
本人代码:
static void Main(string[] args)
{
int count=0;
bool flag = false;
count = ReadInt();
Console.WriteLine(".....................................................");
Console.WriteLine();
int [,] yanghui=new int[count,count]; //定义一个二维数组
int i=0,j=0;
for (i = 0; i < count; i++) //给杨辉三角赋值
{
yanghui[i, 0] = yanghui[i, i] = 1;
for (j = 1; j < i; j++)
{
yanghui[i, j] = yanghui[i - 1, j - 1] + yanghui[i - 1, j];
}
}
if (count % 2 == 1) //输入偶数和奇数是分开打印(输入为奇数时的输出)
{
for (i = 0; i < count; i++)
{
for (int x = (count - i - 1) / 2; x > 0; x--) //补空格
{
Console.Write(" ");
}
if ((i % 2) == 1) //奇数行输出
{
Console.Write(" "); //补空格
for (j = 0; j < (i + 1) / 2 - 1; j++) //输出右半边数
{
Console.Write((yanghui[i, j])); }
Console.Write((yanghui[i, j]));
Console.Write(" "); //补空格
int x = ++j;
for (j = x; j <= i; j++) //输出右半边数
{
Console.Write((yanghui[i, j]));
}
}
else //输出偶数行
{
for (j = 0; j <= i; j++)
{
Console.Write((yanghui[i, j]));
}
}
Console.WriteLine(); //换行
}
}
else //输入为偶数时的输出
{
for (i = 0; i < count; i++)
{
for (int x = (count - i - 1) / 2; x > 0; x--)
{
Console.Write(" ");
}
if ((i % 2) == 1)
{
for (j = 0; j < (i + 1) / 2 - 1; j++)
{
Console.Write((yanghui[i, j]));
}
Console.Write((yanghui[i, j]));
Console.Write(" ");
int x = ++j;
for (j = x; j <= i; j++)
{
Console.Write((yanghui[i, j]));
}
}
else
{
Console.Write(" ");
for (j = 0; j <= i; j++)
{
Console.Write((yanghui[i, j]));
}
}
Console.WriteLine();
}
}
Console.ReadKey();
}
static int ReadInt()
{
int number = 0;
do
{
try
{
Console.WriteLine("请输入一个正整数");
number = Convert.ToInt32(Console.ReadLine());
if (number > 0) //确保输入为正整数 {
break;
}
else
{
continue;
}
}
catch
{
continue;
}
} while (true);
return number; }
|