我正在运行代码,如果我这样写:
int num = 0;
while (num++ < 6) ;
{
Console.WriteLine(num);
}
我得到7的输出
但是如果是这样写的
int num = 0;
while (num++ < 6)
{
Console.WriteLine(num);
}
我得到1,2,3,4,5,6
的输出我真的很困惑为什么仅通过添加多余的分号就可以使输出如此不同。 我知道为什么顶部代码为7,但是为什么不显示所有答案的循环呢?
如果有人可以解释:)真的很感激 谢谢
答案 0 :(得分:2)
分号表示整个while循环就是该行-这意味着之后的{}块不是循环的一部分-而是接下来发生的事情。
所以这个:
int num = 0;
while (num++ < 6) ;
{
Console.WriteLine(num);
}
与写作相同:
int num = 0;
while (num++ < 6)
{
}
Console.WriteLine(num);
看到区别了吗?
答案 1 :(得分:2)
调试代码时,您将看到:
int num = 0;
while (num++ < 6) ; //It checks until num>6 (6 times)
{ //without running the code inside the Curly Brackets
Console.WriteLine(num); // Then it runs just once this line
}
那是因为分号
第二种选择
int num = 0;
while (num++ < 6) // it checks the condition every time
{
Console.WriteLine(num); // it runs this line of code 6 times
}
答案 2 :(得分:1)
我在uni上做一些课程时遇到了这个问题,但从未忘记。基本上,您将用分号终止while循环,而无需在其中运行代码。然后,大括号被编译器删除,您将得到以下结果:
int num = 0;
while (num++ < 6) {}
Console.WriteLine(num);
问题在于,这很难找到,并且如果此代码投入生产,可能会导致重大错误。 TBH我不确定为什么编译器允许这样做或对它有用吗!
答案 3 :(得分:1)
int num = 0; // num is 0
while (num++ < 6) ; // the ; makes this "function" repeat until 6 is reached
{ // since function above has ; this { does nothing
Console.WriteLine(num); // prints where num stopped at, which is 6
} // since function above has ; this } does nothing
=====================================================================================
/* This function is the same as... */
int num = 0;
while (num++ < 6)
{
DoNothing();
}
Console.WriteLine(num);
int num = 0; // num is 0
while (num++ < 6) // no ; makes this "function" do num++ then continue
{ // { start of the instructions
Console.WriteLine(num); // prints where num stopped at, first round is 1
} // end of the instructions
// will go back to while loop until num reaches 6