Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment, decrement by percentage

Tags:

c#

math

I'll try to explain this problem the best way i can with code:

double power = 5000;
//picked up 5 power ups, now need to increase power by 10% per powerup
power += 5 * (power * .10);


//later on...ran into 5 power downs need to decrease power back to initial hp
power -= 5 * (power * .10);//7500 - 3750 -- doesn't work

So what i need is a scaleable solution that gets back to the original value using only the count. Any ideas?

like image 568
Cameron A. Ellis Avatar asked May 08 '09 07:05

Cameron A. Ellis


1 Answers

The best way to do this is using a function. It doesn't have to look exactly like this, but:

class Whatever
{

    private double basePower = 5000;

    public int numPowerUps = 5;

    public double GetActualPower()
    {
        return basePower + (numPowerUps * basePower * 0.1);
    }
}

Just change numPowerUps back to 0 when they run out. This way, it looks a whole lot neater.


An aside:
The reason it's not working is because of the fact that adding and then subtracting percentages doesn't work. For instance:

1. What is 10% of 100?    --> 10
2. Add that to the 100    --> 110
3. What is 10% of 110?    --> 11
4. Subtract that from 110 --> 99

You'll always end up with 99% of your original value. If you really want to take a shortcut, you could instead do this:

1. What is 10% of 100?    --> 10
2. Add that to the 100    --> 110
3. What is (100/11) = 9.09090909...% of 110?    --> 10
4. Subtract that from 110 --> 100

But then you're potentially susceptible to floating point errors. The function way of doing it is not only neater and clearer, but potentially less error-prone.

like image 107
Smashery Avatar answered Sep 28 '22 19:09

Smashery