【问题标题】:How do i Increment every 12th time and Keeping a running total with an object literal and while loop?我如何每 12 次递增一次并使用对象文字和 while 循环保持运行总计?
【发布时间】:2019-09-26 13:10:00
【问题描述】:

一点历史。
这是我上交的一个家庭作业问题。他们希望我在 12 个月付款后在此代码中增加年份,并保持运行总计多少我支付的利息。代码有效或不抛出错误。

问题。
我不知道如何每 12 次迭代增加一个对象文字属性。 (为了表明你已经支付了十二笔款项,并且下一年开始了)我不知道如何保持支付的利息总额。

我尝试过的事情。
我试过在 year 属性中使用循环。要么无法完成,要么我做错了什么。我已经尝试使用 if else 根据付款 ID 增加年份,但它只增加一次。我试过在循环前后增加一年。然后它与付款ID同步,部分成功?

function displayWelcome() {
  printLine();
  console.log('Welcome to the credit card payoff tool.');
  printLine();
  console.log('This program will determine the time it \nwill take to pay off a credit card!');
  printLine();
}
displayWelcome();

function calculateMinimumPayment(balance, interestRate) {    
  var calcMinPay = balance * interestRate; 
  console.log(calcMinPay);  
  return calcMinPay 
}

function generatePaymentId() {  // lines 14 - 22 are a closure function. 
  var count = 0;
  function paymentId() {
    count ++;           
    return count;
  }
  return paymentId;
};
var id = generatePaymentId();



function processPaymentSchedule(balance, interest, minimumPayment) {
  var year = 1;
  var counter = 0;
  while (balance > 0) {
    counter ++;
    year += 0.08333333333;
    var interestDecimal = interest / 100;
    var interestMonthly = interestDecimal / 12;
    var interestPaid = balance * interestMonthly;
    var princplePaid = minimumPayment - interestPaid;
    var balance = balance - princplePaid;    

    var payment = {
      year: year.toFixed(0), 
      balance: balance.toFixed(2), 
      paymentId: id(), 
      interestPaid: interestPaid.toFixed(2)
    };

    function definePayment() {
      console.log(payment);  
    } 

    definePayment();

    if (payment.paymentId > 11) {
      year += 1;
    } 

  }
}

function printLine() {
  console.log('---------------------------------------');
}


processPaymentSchedule (1500, 18, 30);

错误:此代码中没有错误消息,只是不知道如何执行上面列出的操作。

【问题讨论】:

    标签: javascript loops sum increment


    【解决方案1】:

    要确定它是否是迭代中的“每 N 次”计数,您可以使用模运算符 % 从基本整数除法中获取余数。只需将您的计数器变量模数 12,如果计数器大于 0,则它在 12 日、24 日等,通过您的循环运行。

      var counter = 0;
      while (balance > 0) {
        counter ++; 
        if (counter%12==0)
            console.log("You are on a (N*12)th loop run");  
        }
      } 
    

    但是,在计算利息和付款等方面,我建议您在“月”中进行所有计算,然后当您有以月为单位的总数时,如果需要/希望将其转换为年。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-18
      • 2017-07-25
      • 2018-07-09
      • 2020-10-19
      • 2011-11-02
      • 1970-01-01
      相关资源
      最近更新 更多