Java中的复利程序
我正试图编写这个复利程序,在最后有一个do-while循环,但我不知道如何打印出最终金额 以下是我目前掌握的代码:Java中的复利程序,java,while-loop,do-while,Java,While Loop,Do While,我正试图编写这个复利程序,在最后有一个do-while循环,但我不知道如何打印出最终金额 以下是我目前掌握的代码: public static void main(String[] args) { double amount; double rate; double year; System.out.println("This program, with user input, computes interest.\n" + "It allows for
public static void main(String[] args) {
double amount;
double rate;
double year;
System.out.println("This program, with user input, computes interest.\n" +
"It allows for multiple computations.\n" +
"User will input initial cost, interest rate and number of years.");
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the initial cost?");
amount = keyboard.nextDouble();
System.out.println("What is the interest rate?");
rate = keyboard.nextDouble();
rate = rate/100;
System.out.println("How many years?");
year = keyboard.nextInt();
for (int x = 1; x < year; x++){
amount = amount * Math.pow(1.0 + rate, year);
}
System.out.println("For " + year + " years an initial " + amount + " cost compounded at a rate of " + rate + " will grow to " + amount);
String go = "n";
do{
System.out.println("Continue Y/N");
go = keyboard.nextLine();
}while (go.equals("Y") || go.equals("y"));
}
publicstaticvoidmain(字符串[]args){
双倍金额;
双倍费率;
两年;
System.out.println(“此程序通过用户输入计算兴趣。\n”+
“它允许进行多次计算。\n”+
“用户将输入初始成本、利率和年数。”);
扫描仪键盘=新扫描仪(System.in);
System.out.println(“初始成本是多少?”);
金额=键盘.nextDouble();
System.out.println(“利率是多少?”);
速率=键盘.nextDouble();
比率=比率/100;
System.out.println(“多少年?”);
年份=键盘.nextInt();
对于(int x=1;x
}问题是,
金额=金额*数学功率(1.0+费率,年)代码>。您正在用计算的金额覆盖原始金额。您需要一个单独的值来保持计算值,同时仍保持原始值
因此:
然后在输出中:
System.out.println("For " + year + " years an initial " + amount +
" cost compounded at a rate of " + rate + " will grow to " + finalAmount);
编辑:或者,您可以保存一行、一个变量,然后只进行内联计算,例如:
System.out.println("For " + year + " years an initial " + amount +
" cost compounded at a rate of " + rate + " will grow to " +
(amount * Math.pow(1.0 + rate, year)));
在线计算解决了所有问题!另一种方法是给我“finalAmount的未知变量”的错误,谢谢!)你们是awesome@MicahCalamosca哦,对不起。为了使用第一种方法,使用finalAmount
,您需要声明finalAmount
变量,就像声明所有其他变量一样。不管怎么说,我很高兴你能成功。如果您使用了我的解决方案,请接受我的回答。谢谢
System.out.println("For " + year + " years an initial " + amount +
" cost compounded at a rate of " + rate + " will grow to " +
(amount * Math.pow(1.0 + rate, year)));