c# - for 循环覆盖范围增加/减少基于步骤的符号
问题描述
我将如何修改这个 for 循环,使其对 的正值进行Step
计数,但对 的负值进行计数Step
?
对于Step = 2
,预期输出为2 4 6 8 10
对于Step =- 2
,预期输出为10 8 6 4 2
// assume these 3 come from user input
int Lower = 2;
int Upper = 10;
int Step = 2;
for ( int i = Lower; i <= Upper; i += Step )
{
Console.Write(i + " ");
}
解决方案
只要遵守KISS 原则。
您可以将逻辑放入初始化程序和for
语句的条件中:
public static void ForLoopWithDirectionBasedOnStep(int minValue, int maxValue, int step)
{
// Avoid obvious hang
if ( step == 0 )
throw new ArgumentException("step cannot be zero");
// ( initialiser ; condition ; iterator )
for ( int i = step > 0 ? minValue : maxValue; minValue <= i && i <= maxValue; i += step )
Console.Write(i + " ");
}
所以:
ForLoopWithDirectionBasedOnStep(minValue: 2, maxValue: 10, step: 2)
返回:2 4 6 8 10
ForLoopWithDirectionBasedOnStep(minValue: 2, maxValue: 10, step: -2)
返回:10 8 6 4 2
如预期的。
初始化器设置起始值
int i = step > 0 ? minValue : maxValue;
通过使用条件运算符和等价于
int i;
if ( step > 0 )
i = minValue;
else
i = maxValue;
条件
minValue <= i && i <= maxValue
只需检查循环变量是否在 [minValue, maxValue] 范围内。
请注意,错误的输入会自动处理,因为(强调我的):
条件部分(如果存在)必须是布尔表达式。该表达式在每次循环迭代之前进行评估。
所以类似which 会从toForLoopWithDirectionBasedOnStep(minValue: 10, maxValue: 0, step: -2)
倒数的东西不会打印任何东西,因为由于 0 < 10,语句的主体永远不会被执行。0
10
for
推荐阅读
- c++ - 当我使用 cin 输入错误的变量类型时会发生什么?
- laravel - 如何更新 laravel eloquent where 子句?
- tws - reqAllOpenOrders() 无法下载我帐户的数据
- powershell-2.0 - 执行后删除文件夹和脚本
- azure - Azure Log Analytics 未收集日志
- python - Django:具有通用视图的 reverse_lazy()
- android - 安卓短信验证API
- c# - 在 C# 中屏蔽字节数组
- r - 使用 R CMD 检查时避免检查“\notrun”示例
- c - 为什么我的 C http 请求会导致非法指令:4