正解が見つからないので、ここに問題があります。aと。のインデックス(正または負のパーセンテージ)を計算できるようにしたいのです。price
period
期待:
ケース#1
価格:1.000,00
インデックス作成率:5%
正のパーセンテージでの5年間の計算:
1. 1000 x 5^0 = 1000
2. 1000 x 5^1 = 1050
3. 1000 x 5^2 = 1102,50
4. 1000 x 5^3 = 1157.625
5. 1000 x 5^4 = 1215,50625
ケース#2
価格:1.000,00
インデックス作成率:-5%
負のパーセンテージでの5年間の計算:
1. 1000 x -5^0 = 1000
2. 1000 x -5^1 = 950
3. 1000 x -5^2 = 902,50
4. 1000 x -5^3 = 857,375
5. 1000 x -5^4 = 814,50625
結果:
そして、私のJavaコードはこれを出力するので、この負のパーセンテージはうまくいきません。
1000
-5000
-125000
15625000
1175690408
私のコードは非常に単純だと思います:
BigDecimal percentageValue = new BigDecimal("-5");
BigDecimal indexation = percentageValue.divide(ONE_HUNDRED).add(BigDecimal.ONE);
BigDecimal price = new BigDecimal("1000");
for (int i = 0; i < 5; i++)
{
price = price.multiply(indexation.pow(i));
System.out.println(price.intValue());
}
解決:
static final BigDecimal ONE_HUNDRED = new BigDecimal("100");
public static void main(String[] args)
{
BigDecimal percentageValue = new BigDecimal("-5");
BigDecimal indexation = percentageValue.divide(ONE_HUNDRED).add(BigDecimal.ONE);
BigDecimal price = new BigDecimal("1000");
for (int i = 0; i < 5; i++)
{
BigDecimal result = price.multiply(indexation.pow(i));
System.out.println(result);
}
}