bukowski
bukowski

Reputation: 1943

Check if a number is decreasing or increasing

In my loop I have a number that is constantly changing - I need to figure out how to tell if the number is increasing or decreasing:

Some pseudo code that doesnt work :)

    var now:Number; 
    var then:Number;

    function loop():void 
    {
        now = changingNumber;
        then = changingNumber;
        if (now > then) {
            // increasing
        }else {
            // decreasing
        }
    }

Upvotes: 0

Views: 4687

Answers (1)

Marty
Marty

Reputation: 39456

var now:int = 0;
var thn:int = 0;

function loop():void
{
    // Change the number.
    now = changingNumber;

    if(now > thn)
    {
        trace("Got larger.");
    }
    else if(now < thn)
    {
        trace("Got smaller.");
    }
    else
    {
        trace("Maintained value.");
    }

    // Store the changed value for comparison on new loop() call.
    // Notice how we do this AFTER 'now' has changed and we've compared it.
    thn = now;
}

Alternatively, you can prepare a getter and setter for your value and manage an increase or decrease there.

// Properties.
var _now:int = 0;
var _thn:int = 0;


// Return the value of now.
function get now():int
{
    return _now;
}


// Set a new value for now and determine if it's higher or lower.
function set now(value:int):void
{
    _now = value;

    // Comparison statements here as per above.
    // ...

    _thn = _now;
}

This method will be more efficient and not require a loop.

Upvotes: 7

Related Questions