c# - 嵌套 for 循环中的变量
问题描述
我有一个关于 for 循环的问题;代码如下
for (int i = 0; i <= 3; i++)
{
for (int j = 0; j < 2; j++)
{
Console.WriteLine("J");
}
Console.WriteLine("I");
}
此代码的输出是;
JJIJJIJJIJJI
我的问题是:首先 for 循环“i”为 0,条件为真,所以循环进入第二个循环 j 为 0,条件为真。它写入“J”,然后 j++ 正在工作,现在 J 为 1。第二个循环再次写入“J”,然后将其增加到 2,因此第二个 for 循环条件为假,它进入第一个 for 循环,它写入“I”然后增加第一个循环 i 现在是 1 所以第一个 for 循环条件为真,然后它进入第二个:问题从这里开始。J 为 2,在第一个循环条件再次为真之后 J 变为 0 并再次写入 2 J 是如何实现的?
我希望我能正确地告诉你我的问题。太感谢了
解决方案
您的代码,在外部循环结束第一次迭代后,它会继续并重新执行内部循环。但是重新执行意味着重新初始化索引器变量 j=0 所以它再次打印两倍的值“J”
您可以在这两个示例中看到不同之处。第一个是您当前的代码,第二个是没有重新初始化 j 变量
void Main()
{
Test1();
Test2();
TestWithWhile();
}
void Test1()
{
for (int i = 0; i <= 3; i++)
{
// At the for entry point the variable j is declared and is initialized to 0
for (int j = 0; j < 2; j++)
{
Console.Write("J");
}
// At this point j doesn't exist anymore
Console.WriteLine("I");
}
}
void Test2()
{
// declare j outside of any loop.
int j = 0;
for (int i = 0; i <= 3; i++)
{
// do not touch the current value of j, just test if it is less than 2
for (; j < 2; j++)
{
Console.Write("J");
}
// After the first loop over i the variable j is 2 and is not destroyed, so it retains its exit for value of 2
Console.WriteLine("I");
}
}
最后,第三个示例展示了使用两个嵌套的 while 循环来模仿代码中用于 for 循环的相同逻辑。在这里您可以看到导致变量 j 重新初始化的流程
void TestWithWhile()
{
int i = 0; // this is the first for-loop initialization
while (i <= 3) // this is the first for-loop exit condition
{
int j = 0; // this is the inner for-loop initialization
while (j < 2) // this is the inner for-loop exit condition
{
Console.Write("J");
j++; // this is the inner for-loop increment
}
Console.WriteLine("I");
i++; // this is the first for-loop increment
}
}
推荐阅读
- python - 如何将用户输入写入 HTML 文件?
- amazon-s3 - AWS Amplify 中嵌套 URL 路径的意外令牌“<”
- python - 将从 HTML 表中提取的文本分配给变量以供以后使用——Beautiful Soup / Python 3.7
- python - 更新 matplotlib 动画中每个绘图的 y 轴范围
- javascript - 有没有办法找出 iframe 的内容是否发生了变化?
- r - 如何在连续较少的行上对一列求和?
- css - 如何更改primeng自动完成倍数的宽度?
- coldfusion - 查询结果中缺少 GENERATEDKEY
- c - 从 C 中的 ispunct() 返回排除某些标点符号
- python - 如何从列表中或从数据中自动获取子图标题