第六章第七题(金融应用:计算未来投资回报值)(Financial application: compute the future investment value)
*6.7(金融应用:计算未来投资回报值)开发一个函数用于根据指定的投资期限以及固定的投资收益率来确定未来的投资收益总额;该数值基于编程练习题2.21所提及的具体公式进行计算得出。
使用下面的方法头:
public static double calculateFutureInvestmentValue(double initialInvestment, double monthlyInterestRate, int investmentTerm)
例如:futureInvestmentValue(10000,0.05/12, 5) 返回 12833.59。
开发一个测试程序用于引导用户提供具体的初始投资金额(如1,000元)以及预期年利率水平(如9.25%),随后系统将计算并展示从第一年开始到第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)Devise a procedure to calculate the future investment value at a prescribed interest rate over a designated time period. The computed amount is derived from the formula outlined 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 requests the user to input the investment amount (for instance, 1,000) and the interest rate (such as 9%) along with
the program will display a table showing the future values for each year from one to thirty.
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;
}
}
java

效果:


编写程序时应注重良好习惯的养成:
1.文件名称必须使用英文且尽量具体;
2.注释内容必须是英文;
3.变量命名需具体明确、采用驼峰式命名法;
4.保持代码风格的一致性(避免某处使用下划线表示变量名而另一处使用驼峰式);
5.遵循小驼峰命名法(如方法名)和大驼峰命名法(如类名),常量则采用全部大写加下划线的方式命名;
6.学习代码编辑器的基本快捷键操作(例如快速缩进、对齐等功能),以提高编程效率
