在循环中可以得到控制变量的起始值和结束值

本文关键字:控制变量 结束 循环 | 更新日期: 2023-09-27 18:20:38

标题说明了一切,但我将添加一个代码示例以使其更加清晰。

Random r = new Random(); 
for (int i = r.Next(0, 5); i < r.Next(6, 20); i++)
{
    int start = ?
    int end = ?
}

在循环中可以得到控制变量的起始值和结束值

将开始和结束的声明移动到循环外:

Random r = new Random(); 
int start = r.Next(0, 5);
int end = r.Next(6, 20);
for (int i = start; i < end; i++)
{
    // Your code goes here.
    // If you want to generate a new end criteria for each iteration in a similar way 
    // as your example, you need to add this to the end of the loop:
    end = r.Next(6, 20); 
}

在for循环标准块中运行i < r.Next(6, 20)会为每个迭代生成一个新的数字,这可能不是您想要的。