有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何创建一个储蓄银行系统,程序在余额翻倍后停止循环

我的任务是创建一个按描述运行的程序,用Java编程:

Illustrate the growth of money in a savings account. The user enters the initial amount (as a decimal) and the interest rate which are used to calculate the number of years until the money doubles and the number of years until the money reaches a million dollars. (you will need to use more than 1 loop).

Note: The balance at the end of each year is

(1 + r) * balance

where balance is the previous balance, and r is the annual rate of interest in decimal form.

但是,我在代码中找不到错误。结果是,它不断地写下“你的余额将翻倍”,然后这个数字无限增长

以下是代码:

Scanner input = new Scanner(System.in); double years = 0; double futureVaule;

    System.out.print("Please enter the amount of money you would like to deposit, as a decimal:\n>>");
    double balance = input.nextDouble();
    
    System.out.print("Please enter the interest rate of your deposit, as a percent:\n>>");
    double r = input.nextDouble();
    
    do
    {
        futureValue = (1 + r) * balance;
        years = years + 1;
        System.out.println("Your balance will double in " 
                + Math.round(years) + " year(s).");
        
        
    }while(futureValue <= balance*2);

共 (1) 个答案

  1. # 1 楼答案

    这应该管用

    futureValue = balance;
    double doubleBalance = balance*2;
    
      while(futureValue <= doubleBalance)
         {
               futureValue += futureValue * (( 1 + r)/100);
               years++;
         }
    
      System.out.println("Your balance will double in " 
                            + years + " year(s).");