简体   繁体   English

减量和增量值?

[英]Decrement and increment value?

I have min and max params: 我有最小和最大参数:

var min = 30;
var max = 35;

var num = 33;

Also there is timer with step 100 milliseconds. 还有一个计时器,步长为100毫秒。 On body timer I have code: 在身体计时器上,我有代码:

if (num < max)
{
    // Step 1
    num = num + step;    
}

if (num >= max) 
{
     // Step 2
    num = num - step;
}

if (num <= min) 
{
    num = num + step;
}

Problem is that if num = 34.98 works step 1 (34.99 + 0,05), then step 2 . 问题是,如果num = 34.98可以执行步骤1 (34.99 + 0,05),则可以执行步骤2 So in this step I get infinity loop. 因此,在这一步中,我得到了无限循环。 How I can do that if num > max then do decrement to min ? 如果num > max我该怎么做,然后减到min

Well, you may use an else if for the second if (and an else for the third) 好吧,您可以在第二个if使用else if if (对于第三个if使用else

So you could only enter one condition at each loop. 因此,每个循环只能输入一个条件。

You could then simplify your code to this (assuming min < max, the right part of the or clause could be removed) 然后,您可以将代码简化为此(假设min <max,可以删除or子句的右侧)

if (num < max || num <= min) //remove num <= min and throw an exception if max < min could be also done...
   num += step;
else
   num -= step;

which could also be (if min < max) 也可能是(如果min <max)

num = num < max 
         ? num + step 
         : num - step;

You can just use this one line of code : 您可以只使用这一代码:

  num += num >= max || num <= min? (step = step*-1) : step;

Example: 例:

static void Main(string[] args)
{
        var min = 31;
        var max = 33;

        double num = 32;

        double step = 0.10;            

        while (true)
        {
            Console.Clear();

            num += num >= max || num <= min? (step = step * -1) : step;

            Console.Write(num);
            Thread.Sleep(200);
        }
}

Output: LINK 输出: LINK

Instead of using if s, use else if and else 而不是使用if s,而是使用else ifelse

if (num < max)
    num = num + step;
else if (num >= max)
    num = num - step;
else
    num = num + step;

Then remove redudant if (Note that num < max || num <= min equals num < max ) 然后删除冗余( if注意( num < max || num <= min等于num < max ))

if (num < max)
    num = num + step;
else if (num >= max)
    num = num - step;

It could be shorten to num += num < max ? step : step * -1; 它可以缩短为num += num < max ? step : step * -1; num += num < max ? step : step * -1;

I have done such: 我已经做到了:

if ((num + step) <= max && flag_d == 0)
            {
                num = num + step;
            }
            else {

                if (num <= min) {
                    flag_d = 0;
                }

                flag_d = 1;
                num = num - step;
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM