سؤال

I have this function and I was trying to get a list of all the calculations.

f(x) = (100)(1.1)^X

How do I calculate this out in Java. I tried a for loop to get the value of x and the end result of y, but that didn't work. Might have been my code inside. I tried to get the exponent of 1.1 and the multiply that by 100, is this correct?

for(int i = 1; i<=15; i++){
     int expcalc = (int) Math.pow(1.1, i);
     int finalcalc = price * expcalc;
     System.out.println(" " + finalcalc);
}

What am I doing wrong here?

هل كانت مفيدة؟

المحلول

Why are you casting the result as an int? That will drop everything past the decimal point. Declare expcalc and finalcalc as double instead to obtain an accurate result.

double expcalc = Math.pow(1.1, i);
double finalcalc = price * expcalc;

نصائح أخرى

Use BigDecimal if you're using pow() and decimal values, and ESPECIALLY ON MONEY

Assuming your interpretation is correct,

BigDecimal price = new BigDecimal("0.0"); //change this value to your price
for(int i = 1; i<=15; i++){
    BigDecimal expcalc = new BigDecimal("1.1").pow(i);
    BigDecimal finalcalc = price.multiply(expcalc);
    System.out.println(" " + finalcalc);
}

Avoid using double/float on monetary computations.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top