Java中的复利程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19150336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compounding interest program in Java
提问by Micah Calamosca
I'm trying to write this compounding interest program with a do while loop at the end and I cannot figure out how to print out the final amount.
我试图在最后用 do while 循环编写这个复利程序,但我不知道如何打印出最终金额。
Here is the code I have so far :
这是我到目前为止的代码:
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"));
}
}
}
回答by nhgrif
The trouble is, amount = amount * Math.pow(1.0 + rate, year);
. You're overwriting the original amount with the calculated amount. You need a separate value to hold the calculated value while still holding the original value.
麻烦的是,amount = amount * Math.pow(1.0 + rate, year);
。您正在用计算出的金额覆盖原始金额。您需要一个单独的值来保存计算出的值,同时仍保留原始值。
So:
所以:
double finalAmount = amount * Math.pow(1.0 + rate, year);
Then in your output:
然后在你的输出中:
System.out.println("For " + year + " years an initial " + amount +
" cost compounded at a rate of " + rate + " will grow to " + finalAmount);
EDIT: Alternatively, you can save a line, a variable, and just do the calculation inline, as such:
编辑:或者,您可以保存一行、一个变量,然后直接进行计算,如下所示:
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)));