淨現值程式碼

想不起来好名字發表於2024-03-12
import java.util.Scanner;

public class Main {


public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
System.out.println("請輸入成本");
double chengben = sc.nextDouble();
System.out.println("請輸入貼現率");
double rate = sc.nextDouble();
System.out.println("請輸入年限");
int year = sc.nextInt();
//定義一個陣列
double[] flows = new double[year];
for (int i = 0; i < year; i++) {
System.out.println("請輸入第" + (i + 1) + "年的錢");
flows[i] = sc.nextDouble();

}
double npy = 0;
npy = npvjisuan(chengben, flows, rate, year);


double originalValue = npy; // 需要四捨五入的原始值
double roundedValue = Math.round(originalValue * 100.0) / 100.0; // 進行四捨五入並保留兩位小數


System.out.println(roundedValue);


}

public static double npvjisuan(double chengben, double[] liu, double rate, int year) {
double npv = chengben;
for (int i = 0; i < year; i++) {
npv += liu[i] / Math.pow(1.0 + rate, i + 1);

}


return npv;
}


}

相關文章