我正在写一个Java程序。它应该打印出年终账户余额、今年的投资、年度回报和年度数量。例:
第一年--投资10,000美元@ 10%
我的代码打印了六年,但值与第一年相同。那么循环有什么问题吗?非常感谢。这里我的代码:
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今年投资年收益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年数
发布于 2014-04-09 04:47:17
看来你也只是在计算每年节省的利息。
更改:
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);发布于 2014-04-09 04:47:02
你不能保持一个跑步的总数。
看起来可能是第三或第四周的教程,但这是一个公平的问题,至少你问了什么问题。
尝试:total += (amountInvested + interest);
括号是不需要的,但我通常会发现它们是一个很好的逻辑分组设备。
发布于 2014-04-09 04:48:16
检查下面的循环,您没有像您所说的那样添加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循环的最后一行。
https://stackoverflow.com/questions/22952939
复制相似问题