gpt4 book ai didi

c# - 在for循环C#中使用括号和不使用括号的区别

转载 作者:太空宇宙 更新时间:2023-11-03 17:50:03 24 4
gpt4 key购买 nike

以下代码的输出与第二个代码的输出不同谁能解释一下这个问题?

代码 1:

for(int i = 1; i <= intInput; i++)
{
for(int j = 1; j<=i; j++)
{
Console.Write('+');
Console.WriteLine();
}
}
if intInput is 4 Ouput is:
+
+
+
+

代码 2:

for(int i = 1; i <= intInput; i++)
{
for(int j = 1; j<=i; j++)
Console.Write('+');
Console.WriteLine();
}
if intInput is 4 Ouput is:

+
++
+++
++++

我知道这行代码是如何工作的,但我不明白括号对这两个代码有什么区别?

最佳答案

当你写的时候;

for(int j = 1; j <= i; j++)
{
Console.Write('+');
Console.WriteLine();
}

Console 行都有效,直到 j 循环结束。

但是当你写的时候

for(int j = 1; j <= i; j++)
Console.Write('+');
Console.WriteLine();

只有第一个Console 工作,直到j 循环结束。这就是为什么第二个等于;

for(int j = 1; j<=i; j++)
{
Console.Write('+');
}
Console.WriteLine();

如果循环中包含一个语句,则大括号可以省略。但使用它们总是是更好的方法。

阅读:Why is it considered a bad practice to omit curly braces?

关于c# - 在for循环C#中使用括号和不使用括号的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33564698/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com