【问题标题】:How Do I Use Loops to Find Sums in Array?如何使用循环在数组中求和?
【发布时间】:2019-10-29 17:16:33
【问题描述】:

所以我需要使用一个循环来用总量填充一个数组。总金额将是花费的金额加上一个百分比的礼品卡。所以

total = amountSpent + amountSpent*(1+giftCard)

我无法获得总数。消费金额和礼品卡金额都是使用 math.random 随机生成的。消费金额和礼品卡金额分别位于不同的数组中,消费金额介于 0 到 500 之间,礼品卡金额介于 0 到 50 之间。

 var spent = new Array(5);
 for (var i = 0; i < 5; i++)
 {
      randS = Math.floor(Math.random() * 500);
      spent[i] = randS;
 }

 var gifts = new Array(5);
 for (var i = 0; i < 5; i++)
 {
      randG= Math.floor(Math.random() * 50);
      gifts[i] = randG;
 }

这些是我使用 for 循环填充数组的方法。我现在应该创建一个新数组并使用循环来计算总数。我为消费金额和礼品卡金额定义了 2 个变量,但我不确定它们是否调用了正确的号码。

 var totals = new Array(5);
 var tSpent = spent;
 var tGifts = gifts;
 for (var i = 0; i < 5; i++)
 {
      totals[i] = tSpent + (1 + (tGifts / 100)) * tSpent;
      totals[i] = totals[i].toFixed(2);
 }

我知道这个数组是问题所在,因为其他两个数组显示的数字很好。我还必须将礼品卡金额转换为小数,并确保总数为小数点后 2 位。

【问题讨论】:

  • 您忘记索引您的tSpenttGifts 对吧?一行应该说:totals[i] tSpent[i] + ( 1 + (tGifts[i] / 100)) * tSpent[i]; ??

标签: javascript html arrays for-loop


【解决方案1】:

您可以像这样在一个循环中编写整个代码:

var spent=[],gifts=[],totals=[];
for(let i = 0; i < 5; i++){
    spent[i] = Math.floor(Math.random() * 500);
    gifts[i] = Math.floor(Math.random() * 50);
    totals[i] = spent[i] + (1 + gifts[i]/10)*spent[i]
    totals[i] = totals[i].toFixed(2);
}

【讨论】:

    【解决方案2】:

    就我能理解您的问题而言,我觉得您的做法是正确的,只是需要在您的代码中做一个小的更正。

     var totals = new Array(5);
     var tSpent = spent;
     var tGifts = gifts;
     for (var i = 0; i < 5; i++)
     {
          totals[i] = tSpent[i] + (1 + (tGifts[i] / 100)) * tSpent[i];
          totals[i] = totals[i].toFixed(2);
     }
    

    此外,您的数组 tSpendtGifts 调用了正确的数字,尽管它们看起来是多余的,除非您稍后在代码中为它们计划了一些东西。如果不是,他们只是直接参考您的实际可变支出和礼物。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-22
      • 1970-01-01
      • 2017-06-02
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多