import java.util.Arrays;
import java.util.Scanner;
public class InvestmentReturnCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 获取项目投资额
System.out.print("请输入项目投资额: ");
double investmentAmount = scanner.nextDouble();
// 获取项目未来一段时间内的现金流量
System.out.print("请输入项目未来一段时间内的现金流量(投资几年): ");
double[] cashFlows = new double[scanner.nextInt()];
for (int i = 0; i < cashFlows.length; i++) {
System.out.print("请输入第" + (i + 1) + "年的现金流量: ");
cashFlows[i] = scanner.nextDouble();
}
// 计算投资回收率
double npv = calculateNetPresentValue(investmentAmount, cashFlows);
double irr = calculateInternalRateOfReturn(investmentAmount, cashFlows);
System.out.println("净现值为: " + npv);
System.out.println("投资回收率为: " + irr);
}
/**
* 计算净现值
*/
public static double calculateNetPresentValue(double investmentAmount, double[] cashFlows) {
double npv = -investmentAmount;
for (int i = 0; i < cashFlows.length; i++) {
npv += cashFlows[i] / Math.pow(1 + calculateInternalRateOfReturn(investmentAmount, cashFlows), i + 1);
}
return npv;
}
/**
* 计算内部收益率
*/
public static double calculateInternalRateOfReturn(double investmentAmount, double[] cashFlows) {
double irr = 0;
double npv = 0;
double irrStep = 0.0001;
double minValue = Double.MAX_VALUE;
for (double rate = 0; rate <= 1; rate += irrStep) {
npv = -investmentAmount;
for (int i = 0; i < cashFlows.length; i++) {
npv += cashFlows[i] / Math.pow(1 + rate, i + 1);
}
double diff = Math.abs(npv);
if (diff < minValue) {
minValue = diff;
irr = rate;
}
}
return irr;
}
}
在这个代码中,我使用了两个方法来计算投资回收率和净现值:
● calculateNetPresentValue:该方法用于计算项目的净现值。净现值是指项目未来现金流量的现值总和与投资金额的差值。该方法的参数包括项目的投资金额和未来一段时间内的现金流量数组,返回值为净现值。
● calculateInternalRateOfReturn:该方法用于计算项目的内部收益率。内部收益率是指使项目的净现值等于零的贴现率。