繁体   English   中英

WHILE循环中的布尔语句没有意义吗?

[英]Boolean Statement in WHILE loop doesn't make sense?

我的while声明对我来说似乎没有任何意义,即使它可行。
我希望它在countYears 小于 timeLimit的情况下计算利息。...因此,如果将timeLimit设置为5,则它应该仅计算5年的利息,但以我读取当前while语句的方式,似乎没有这么说。 也许我只是读错了?

public class RandomPractice {
public static void main(String[] args)
{
    Scanner Keyboard = new Scanner(System.in);
    double intRate, begBalance, balance;
    int countYears, timeLimit;

    System.out.println("Please enter your current investment balance.");
    begBalance = Keyboard.nextDouble();

    System.out.println("Please enter your YEARLY interest rate (in decimals).");
    intRate = Keyboard.nextDouble();

    System.out.println("Please enter how long (in years) you would like to let interest accrue.");
    timeLimit = Keyboard.nextInt();

    balance = begBalance * (1 + intRate);
    countYears = 0;

    /* The way I read this while statement is as follows 
     * "While countYears is GREATER than the timeLimit...calculate the balance"
     * This makes no logical sense to me but I get the correct output? 
     * I want this code to calculate the investment interest ONLY as long as
     * countYears is LESS than timeLimit **/
    while (countYears >= timeLimit)
    {
        balance = balance + (balance * intRate);
        countYears++;
    }       

    System.out.println(balance);

  }
}

您所拥有的代码无法生成正确的数据,我的成绩单以每年1%的速度记录了八年:

Please enter your current investment balance.
100
Please enter your YEARLY interest rate (in decimals).
.01
Please enter how long (in years) you would like to let interest accrue.
8
101.0

换句话说,只增加一年的利息,而不是八年。

因此,或者您的编译器完全是搞砸了,您的代码不是您想像的那样,或者您用来检查兴趣度计算的任何测试数据和/或方法都有些缺乏。

首先,正如您所countYears < timeLimit那样,您需要将条件更改为countYears < timeLimit

此外,您还需要在循环之前删除初始利息计算因为这意味着您存入钱后将获得全年的利息。 有了这两个更改:

balance = begBalance;
while (countYears < timeLimit) {
    balance = balance + (balance * intRate);
    countYears++;
}       

然后您将获得正确的值

Please enter your current investment balance.
100
Please enter your YEARLY interest rate (in decimals).
.01
Please enter how long (in years) you would like to let interest accrue.
8
108.28567056280801

如果将循环切换为<= ,则根本不会执行循环,这是正确的。

现在,您的输出是在循环外部计算的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM