我找到了一种方法,用一个嵌套的for循环显示以18结尾的三角形的上半部分。我无法弄清楚如何在嵌套的for循环中显示下半部分(它必须在嵌套的for循环中)。另外,如何使颜色从绿色和红色互换?有什么提示吗?
以下是我所拥有的:
int n1, n2, n3;
// Top Triangle nested for loop
for (n1 = 2; n1 <=18; n1++)
{
for (n2 = 2; n2 <= n1; n2++)
{
Console.Write("{0} ", n2);
n2++;
}
n1++;
Console.WriteLine();
}
// Bottom triangle nested for loop
// This is where I'm stuck
答案 0 :(得分:0)
底部三角形部分:
// Bottom triangle nested for loop
for (n1 = 16; n1 > 2; n1 -= 2)
{
for (n2 = 2; n2 <= n1; n2 += 2)
{
Console.Write("{0} ", n2);
}
Console.WriteLine();
}
更改颜色的完整代码:
static bool _isRedColor = true;
static void Main(string[] args)
{
int n1, n2;
// Top Triangle nested for loop
for (n1 = 2; n1 <= 18; n1 += 2)
{
_isRedColor = true;
for (n2 = 2; n2 <= n1; n2 += 2)
{
SetConsoleColor();
Console.Write("{0} ", n2);
//n2++;
}
//n1++;
Console.WriteLine();
}
// Bottom triangle nested for loop
for (n1 = 16; n1 > 2; n1 -= 2)
{
_isRedColor = true;
for (n2 = 2; n2 <= n1; n2 += 2)
{
SetConsoleColor();
Console.Write("{0} ", n2);
}
Console.WriteLine();
}
}
private static void SetConsoleColor()
{
if (_isRedColor)
{
Console.ForegroundColor = ConsoleColor.DarkRed;
_isRedColor = !_isRedColor;
}
else
{
Console.ForegroundColor = ConsoleColor.DarkGreen;
_isRedColor = !_isRedColor;
}
}
答案 1 :(得分:0)
for (n1 = 2; n1 <= 18; n1++)
{
for (n2 = 2; n2 <= n1; n2++)
{
Console.Write("{0} ", n2);
n2++;
}
n1++;
Console.WriteLine();
}
for (n1 = 2; n1 <= 18; n1++)
{
for (n2 = 2; n2 <= 18 - n1; n2++)
{
Console.Write("{0} ", n2);
n2++;
}
n1++;
Console.WriteLine();
}
答案 2 :(得分:0)
你的问题很有意思,所以我试了一下,想在这里用working example in fiddle分享我的发现,请注意我已经使用了一些额外的变量以及重命名的现有变量希望它赢了&#39 ;误导你。请仔细阅读以下内容,如果您需要任何说明,请告知我们
int loopLimit = 18;
int outerLoopCounter, innerLoopCounter = 2, upperBoudIterator = 2;
// Top Triangle nested for loop
for (outerLoopCounter = 0; outerLoopCounter <= 18; outerLoopCounter++)
{
innerLoopCounter = 2;
while (innerLoopCounter <= upperBoudIterator)
{
if (innerLoopCounter <= loopLimit)
Console.Write("{0} ", innerLoopCounter);
innerLoopCounter += 2;
};
if (innerLoopCounter > loopLimit)
loopLimit -= 2;
upperBoudIterator += 2;
Console.WriteLine();
}
答案 3 :(得分:0)
所以我尝试了这个作为一个学术练习,这是我的尝试。使用我在评论中提到的方法和属性,你可以用一个循环嵌套循环对来解决这个问题:
int max = 18;
int cursorX = 0;
int count, digits;
for (int i = 2; i <= max; i += 2)
{
count = max - i + 1;
digits = i.ToString().Length;
Console.ForegroundColor = (i % 4 == 0) ? ConsoleColor.Red : ConsoleColor.Green;
for (int y = 0; y < count; y++)
{
Console.SetCursorPosition(cursorX, y + (i / 2) - 1);
Console.Write(i);
}
cursorX += digits + 1;
}
结果: