For 循环直接跳到最后
本文关键字:最后 循环 For | 更新日期: 2023-09-27 18:32:43
我开始学习C#,我的一个作业遇到了问题。任务是创建一个由星星组成的金字塔。高度由用户输入指定。
出于某种原因,我的第一个for
循环跳到最后。在调试时,我注意到变量height
接收bar
的值,但之后它会跳到最后。我不知道为什么,因为代码对我来说似乎很好。
do
- while
循环用于要求用户输入新值,以防输入的值0
或更低。
using System;
namespace Viope
{
class Vioppe
{
static void Main()
{
int bar;
do
{
Console.Write("Anna korkeus: ");
string foo = Console.ReadLine();
bar = int.Parse(foo);
}
while (bar <= 0);
for (int height = bar; height == 0; height--)
{
for (int spaces = height; spaces == height - 1; spaces--)
{
Console.Write(" ");
}
for (int stars = 1; stars >= height; stars = stars * 2 - 1)
{
Console.Write("*");
}
Console.WriteLine();
}
}
}
}
for
循环中的条件是必须保持为真才能进入循环体的条件。所以这个:
for (int height = bar; height == 0; height--)
应该是:
for (int height = bar; height >= 0; height--)
否则,执行赋值,然后它将检查height
是否为 0,如果不是(必然是这种情况),那就是循环的结束。
有关详细信息,请参阅 MSDN 文档以了解for
循环。
试试这个:-
for (int height = bar; height >= 0; height--)
而不是
for (int height = bar; height == 0; height--)
while 循环仅在 bar 小于或等于零时退出。所以最初在 for 循环中高度 = 柱(大于 0)。检查高度是否等于零,这是错误的。您要检查>= 0。
for (int height = bar; height == 0; height--)
你的条件:height == 0;
永远不会是真的。
为了真实,身高必须0
,
为了0
高度,酒吧必须0
。
如果bar
是0
,那么你甚至不会因为这个无限的while循环而进入你的for循环:
while (bar <= 0);