*6.7(金融应用:计算未来投资回报值)编写一个方法,计算按照给定的年数和利率计算未来投资回报值,未来投资回报值是用编程练习题2.21中的公式计算得到的。
使用下面的方法头:
public static double futureInvestmentValue(double investmentAmount,double monthlyInterestRate, int years)
例如:futureInvestmentValue(10000,0.05/12, 5) 返回 12833.59。
编写一个测试程序,提示用户输入投资额(例如1000)、利率(例如9%),然后打印年份从1到30年的未来投资回报值,如下所示:
The amount invested:1000
Annual interest rate:9
Years Future Value
1 1093.80
2 1196.41
....
29 13467.25
30 14730.57
*6.7(Financial application: compute the future investment value)Write a method that computes future investment value at a given interest rate for a specified number of years. The future investment is determined using the formula in Programming Exercise 2.21.
Use the following method header:
public static double futureInvestmentValue(double investmentAmount,double monthlyInterestRate, int years)
For example,futureInvestmentValue(10000,0.05/12, 5) returns 12833.59.
Write a test program that prompts the user to enter the investment amount (e.g., 1,000) and the interest rate (e.g., 9%) and
prints a table that displays future value for the years from 1 to 30, as shown below:
The amount invested:1000
Annual interest rate:9
Years Future Value
1 1093.80
2 1196.41
....
29 13467.25
30 14730.57
下面是参考答案代码:
import java.util.*;
public class ComputeTheFutureInvestmentValueQuestion7 {
public static void main(String[] args) {
double amount,rate;
Scanner inputScanner = new Scanner(System.in);
System.out.print("The amount invested:");
amount = inputScanner.nextDouble();
System.out.print("Annual interest rate:");
rate = inputScanner.nextDouble();
System.out.println("Years\tFuture Value");
for(int i = 1;i <= 30;i++)
System.out.printf("%d\t%.2f\n",i ,futureInvestmentValue(amount, rate/1200, i));
inputScanner.close();
}
public static double futureInvestmentValue(double investmentAmount,
double monthlyInterestRate, int years) {
double FutureInvestmentValue = investmentAmount
* Math.pow((1 + monthlyInterestRate),(years * 12));
return FutureInvestmentValue;
}
}
运行效果:
注:编写程序要养成良好习惯
1.文件名要用英文,具体一点
2.注释要英文
3.变量命名要具体,不要抽象(如:a,b,c等等),形式要驼峰化
4.整体书写风格要统一(不要这里是驼峰,那里是下划线,这里的逻辑段落空三行,那里相同的逻辑段落空5行等等)
5.普通变量,方法名要小驼峰,类名要大驼峰,常量要使用全部大写加上下划线命名法
6.要学习相应的代码编辑器的一些常用快捷键,如:快速对齐等等