【问题标题】:I have a method compute(int months) but it does not iterate as I want it to be我有一个方法 compute(int months) 但它不会像我想要的那样迭代
【发布时间】:2019-03-07 04:40:23
【问题描述】:

这是我的方法compute(),需要多少个月:

 public double compute(int months){
        double balance = employee.getSalary();
        double newBalance=0;
        double monthlyInterest = (bankName.getInterestRate())/12;
        double annualRaise = employee.getAnnualRaise();

if (months <=12){
      for (int i = 1; i <= months; i++){
        newBalance = (newBalance+balance)*(1+monthlyInterest);
      }
      return newBalance;
    }

    else{

      int cycle = months/12;

      while (cycle >0){
        for (int i = 1; i <= 12; i++){
          newBalance = (newBalance+balance)*(1+monthlyInterest);
        }
        cycle--;

        months = months - 12; //remainder of months

        balance = balance*(1+annualRaise/100); //new starting salary

      }

      for (int k = 1; k <= months; k++){
        newBalance = (newBalance+balance)*(1+monthlyInterest);
      }
      return newBalance;
    }

  }

为了给出一个上下文,

  1. 余额:是员工在每个月初获得的固定月薪
  2. monthly interest : 是每月根据员工银行余额计算的利率
  3. 年加薪 : 是员工在新年伊始每月工资的加薪

我的输入示例如下:

Bill Jobs 54000.0 0 0.012 13

Bill Jobs 为员工,余额为 54K,年利率为 0%,银行年利率为 1.2%,计算时间为 13 个月以上。我想要的输出应该是:

Bill Jobs: salary is 54K, annual raise is 0% has balance of 706933.71 

当我调用计算方法时计算 706933.71 的余额,但我最终得到了

Bill Jobs: salary is 54K, annual raise is 0% has balance of 705852.63

13 个月后他的余额是 705852.63。

【问题讨论】:

  • 我已经运行了你的代码,但它似乎给出了正确的结果。您能否编辑问题以包含您的输入以及您如何调用该方法?
  • 我在months &lt;= 12 所在的部分看不到任何错误。我认为else 块的末尾有一个错误,但它不会影响months = 2 的情况。我建议你用你的调试器逐步完成这个,看看到底发生了什么。
  • @Mark 我已经进行了编辑以包含一个示例!
  • @Cheryl,我不知道你为什么会得到那个输入,但是当我运行你的代码时,我得到了706933.7101622699,根据你的问题是正确的。尝试使用调试器并确保正确传递输入值

标签: java loops iteration


【解决方案1】:

请参阅下面的基本计算方法,以计算每月加息 1.5% 的工资。您可以根据自己的要求进行修改。

import java.util.Scanner;

public class Salary {

public static void main(String[] args) {

    double salary = 24000;
    double interest = 1.5;
    double total = 0;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the month = ");
    int month = sc.nextInt();
    if(month != 0 && month  < 13){
        for(int i=1; i <= month; i++){
            salary += total;
            total = (salary + (salary * (interest/100)))  ;
        }
        System.out.println("salary with interest "+total);
    }else{
        System.out.println("Enter the month from 1-12");
    }


   }

}

【讨论】:

  • 我不认为这里有任何 Cheryl 不知道该怎么做的事情。她的要求比这复杂得多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-06
  • 1970-01-01
  • 2022-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多