首页 > 解决方案 > 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 + " ");
}

标签: c#for-loop

解决方案


只要遵守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,语句的主体永远不会被执行。010for


推荐阅读