[英]Stuck with do-while loop
我正在編寫一個Java程序。 它應該打印出年末帳戶余額,今年投資,年收益和年數。 例如:
第一年–在10%的情況下投資10,000美元,您最終將獲得$ 11,000第二年–在您已經擁有的$ 11,000之上再投資10,000美元,所以現在您有$ 21,000,並且您的年收益為$ 2,100,因此最終您將獲得$ 23,100並繼續努力直到達到6年
我的代碼打印了全部6年,但與第1年的值相同。那么循環有什么問題嗎? 非常感謝。 這是我的代碼:
import java.io.*;
import java.util.*;
import java.text.*;
public class ExamFive {
public static void main(String[] args) {
final int MAX_INVESTMENT = 5000000;
double goalAmount;
double amountInvested;
double annualRate;
double interest;
double total= 0;
int year = 0;
Scanner myScanner = new Scanner(System.in);
System.out.println("Enter your investment goal amount: ");
goalAmount = myScanner.nextDouble();
if (goalAmount > MAX_INVESTMENT) {
System.out.println("Your goal is outside the allowed 5,000,000 limit");
}
System.out.println("Enter the amount annually invested: ");
amountInvested = myScanner.nextDouble();
System.out.println("Enter the expected annual return rate (ex 6.50): ");
annualRate = myScanner.nextDouble();
do {
interest = amountInvested * (annualRate / 100);
total = amountInvested + interest;
year++;
System.out.println("Yearend account balance " + total +
" Invested this year " + amountInvested + " Annual return " + interest
+ " number of years " + year);
} while (total < MAX_INVESTMENT && year < 6);
System.out.println(" ");
System.out.println("Your investment goal " + goalAmount);
System.out.println("Your annualinvestment amount " + amountInvested);
System.out.println("Number of years to reach your goal " + year);
}
}
這是輸出:
年末賬戶余額11000.0今年投資了10000.0年回報1000.0年數1年末賬戶余額11000.0今年投資了10000.0年回報1000.0年數2年末賬戶余額11000.0今年投資了10000.0年回報1000.0年數3年末賬戶余額11000.0投資了今年10000.0年收益1000.0年數4年末賬戶余額11000.0年投資10000.0年收益1000.0年數5年末賬戶余額11000.0年本年投資10000.0年收益1000.0年數6
您並沒有保持運行總數。
看起來可能是第3周或第4周的教程,但這是一個公平的問題,至少您問過哪里出了問題。
嘗試: total += (amountInvested + interest);
不需要括號,但是我通常會發現它們是一個很好的邏輯分組設備。
看來您也只是在計算每年節省的利息。
更改:
do {
interest = amountInvested * (annualRate / 100);
total = amountInvested + interest;
year++;
...
} while (total < MAX_INVESTMENT && year < 6);
至:
do {
total += amountInvested;
interest = total * annualRate / 100;
total += interest;
year++;
...
} while (total < MAX_INVESTMENT && year < 6);
檢查下面的循環,您沒有像所說的那樣增加10,000
do {
interest = amountInvested * (annualRate / 100);
total = amountInvested + interest;
year++;
System.out.println("Yearend account balance " + total +
" Invested this year " + amountInvested + " Annual return " + interest
+ " number of years " + year);
}
添加以下行
amountInvested += (total + 10000);
作為do while循環的最后一行
amountInvested,annualRate始終相同。 您不會在循環中遞增或遞減這些值。 因此,它們將始終保持不變。 另外,計算利息的公式不正確,您沒有在任何地方使用年份變量。 它應該是,
do {
interest = amountInvested * (annualRate / 100) * year;
total = amountInvested + interest;
year++;
System.out.println("Yearend account balance " + total +
" Invested this year " + amountInvested + " Annual return " + interest
+ " number of years " + year);
} while (total < MAX_INVESTMENT && year < 6);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.