[英]Novice logic in Java
我正在從書本中學習Java,並且遇到了邏輯問題,我知道代碼沒有達到應有的效果,但是我想了解這個問題,以便更好地了解Java的工作原理並避免更復雜的問題在將來。
我要編寫的程序應該讀入帳戶余額和利率,然后在一年零兩年后給出余額。
第二年的利率應從第一年的總和中計算得出。
但是我的計划是從第一年到第二年增加相同的利息。 因此,在余額為6000且利息為4.25的情況下,第一年的收入為6255.0,第二年的收入為6510.0。 第二年總計我應該得到6520.83,因為第一年的利息也應該獲得計算的利息。
import acm.program.*;
public class BalanceAndIntrest extends ConsoleProgram {
public void run() {
println("This program calculates intrest.");
double balance = readDouble("Enter your balance here: ");
double intrest = readDouble("Enter your intrest rate here: ");
double yearsIntrest = (balance / 100) * intrest;
balance += yearsIntrest;
println("The balance after a year would be £" + balance +".");
balance += yearsIntrest;
println("The balance after two years would be £" + balance +".");
我的邏輯是
它讀入利息年中的余額,將余額除以100,然后再乘以利率來定義利息。 然后將利率添加到余額中,然后再次添加利率,這應該給出不同的利率,因為此時余額的值已更改,但實際上並沒有,它只是計算讀入而不是更新后的余額。
為什么是這樣?
我以為,到程序結束時,余額的值應該是更新的值,以便年利率var應該可以工作..但是,顯然我弄錯了。
如果你寫一個像
double yearsInterest = (balance / 100) * interest;
您沒有從數學意義上定義興趣的含義。 您實際要做的是使用當前由balance
和interest
引用的值來計算interest
。 如果要定義它,只需添加一個方法
private double calculateInterest(double balance, double interest) {
return (balance / 100) * interest;
}
像這樣使用
balance += calculateInterest(balance, interest);
println("The balance after a year would be £" + balance +".");
balance += calculateInterest(balance, interest);
println("The balance after two years would be £" + balance +".");
您需要重新計算第二年的利息,例如:
println("This program calculates intrest.");
double balance = readDouble("Enter your balance here: ");
double intrest = readDouble("Enter your intrest rate here: ");
double firstYearIntrest = (balance / 100) * intrest;
balance += firstYearIntrest;
println("The balance after a year would be £" + balance +".");
double secondYearIntrest = (balance / 100) * intrest;
balance += secondYearIntrest;
println("The balance after two years would be £" + balance +".");
(同樣,當您結束學習Java時:以后不要為了金錢而使用float / double,請始終使用任意精度的十進制整數或您的語言具有的最長整數,並且代表分的小數)
第一年后,您沒有根據更新后的余額重新計算利息:
double balance = readDouble("Enter your balance here: ");
double intrest = readDouble("Enter your intrest rate here: ");
double yearsIntrest = (balance / 100) * intrest;
balance += yearsIntrest;
println("The balance after a year would be £" + balance +".");
// Now the interest must be recomputed, since the balance has changed:
yearsIntrest = (balance / 100) * intrest;
balance += yearsIntrest;
println("The balance after two years would be £" + balance +".");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.