我将尝试用代码解释这个问题的最佳方法:
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
Run Code Online (Sandbox Code Playgroud)
所以我需要的是一个可扩展的解决方案,只使用计数就可以恢复原始值.有任何想法吗?
Sma*_*ery 19
最好的方法是使用一个函数.它不必看起来像这样,但是:
class Whatever
{
private double basePower = 5000;
public int numPowerUps = 5;
public double GetActualPower()
{
return basePower + (numPowerUps * basePower * 0.1);
}
}
Run Code Online (Sandbox Code Playgroud)
只需将numPowerUps更改为0即可.这样,它看起来整整很多.
旁白:
它不起作用的原因是因为添加然后减去百分比不起作用.例如:
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
Run Code Online (Sandbox Code Playgroud)
您总是会得到99%的原始价值.如果你真的想要一个快捷方式,你可以这样做:
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
Run Code Online (Sandbox Code Playgroud)
但是,您可能容易受到浮点错误的影响.这样做的功能方式不仅更整洁,更清晰,而且可能更不容易出错.