PDA

View Full Version : When to use Math.pow??


easyb
10-20-2009, 01:03 PM
Hi techies,
Kindly help me the situation below:

//Interest.java
/*Mr. Brown invests $50,000.00 in a savings account yielding 5 percent interest.
* Assuming that all interest is left on deposit, write java codes to calculate and print
* the amount of money in the account at the end of each year for 10 years.
* Use the following formula for determining these amounts:
* a=P(1+r)n
* Where:
* P is the original amount invested i.e. the principal
* r is the annual interest rate
* n is the number of years
* a is the amount on deposit at the end of the nth year
* */

public class Interest {

public static void main(String[] args) {
double P=50000.00;
double r=0.05;
int n;
for(n=1; n<=10; n++);

System.out.println("The amount at the end of the first year is:" + P*(1+r));

/*this only prints the result for the first year but I would like to use this result as the principal for the second year and the subsequent for the 3rd year and so on..
**/

}

}

Any help is appreciated
Thanks,
Bonny

mmcnitt
10-20-2009, 05:52 PM
i'm not gonna show you in your code so that you can do this :) but here's your solution i think

save more coding and put in a while loop

(ex.)


do
System.out.println("the amount of " + n + " if you add 1 is " + ++n);

while (n<=1000);


That displays your n value, will display your amount and increments the n value all in one. and until the while value is true it keeps running whatever is under the do.

hope this helps

zero++
10-22-2009, 03:53 AM
Like what mmcnitt said.
But first, you should recheck your formula in your code with the given formula

B101T
10-28-2009, 02:02 AM
for(n=1; n<=10; n++);

System.out.println("The amount at the end of the first year is:" + P*(1+r));

/*this only prints the result for the first year but I would like to use this result as the principal for the second year and the subsequent for the 3rd year and so on..
**/


Of course it always prints the result of the first year, your never changing the amount, your always printing P*(1+r).. Now, I am not sure about the formula but it looks like you'll probably need a variable to keep track of the current number and add the interest to it before printing:

for (n = 1; n <= 10; n++)
{
P += P*(1+r);
System.out.println(P);
}