Babaev
Babaev

Reputation: 55

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. 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. So in this step I get infinity loop. How I can do that if num > max then do decrement to min?

Upvotes: 2

Views: 645

Answers (4)

Babaev
Babaev

Reputation: 55

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;
            }

Upvotes: 0

Fabjan
Fabjan

Reputation: 13676

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

Upvotes: 1

Arthur Rey
Arthur Rey

Reputation: 3058

Instead of using ifs, use else if and else

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 = num + step;
else if (num >= max)
    num = num - step;

It could be shorten to num += num < max ? step : step * -1;

Upvotes: 0

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60493

Well, you may use an else if for the second if (and an else for the third)

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)

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)

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

Upvotes: 2

Related Questions