简体   繁体   English

我的 javscript 计算有问题

[英]Having some problem in my calculation with javscript

I am trying to add a the values in an array untill the sum is 1000. I have been trying it using for loop with if condition.我正在尝试在数组中添加一个值,直到总和为 1000。我一直在尝试使用带有 if 条件的 for 循环。 but it doesn't stop in according with sum value.但它并没有根据总和值停止。 example array [110.110.225,130,150,100,240,170,100,110,...] I want the loop to be stopped once the sum of values = 1000 or any other specific sum.示例数组 [110.110.225,130,150,100,240,170,100,110,...] 我希望在值的总和 = 1000 或任何其他特定总和时停止循环。 Need help please.请需要帮助。

can we see an example of your code?我们可以看看您的代码示例吗?

you can use a for loop to check for the sum and exist the loop using break if the sum reaches above your desired value.您可以使用 for 循环检查总和,如果总和超过您的期望值,则使用 break 存在循环。

this will notify about how many numbers were needed to reach 1000 and exist the loop:这将通知需要多少数字才能达到 1000 并存在循环:

for (var i = 0; i < numbers.length ; i++) {

var sum = 0;
sum += numbers[i];

if (sum > 1000) {
  alert(i);
  break;
  }

}
function stopWhenSumEqualsN(n,A) {
  var n=n||500;
  var A=A||[110,110,225,130,150,100,240,170,100,110];
  let obj=A.reduce(function(a,v,i){
    if(a.sum<a.threshold) {
      a.sum+=Number(v);
      a.maxidx+=Number(1);
    }
    return a;
  },{sum:0,maxidx:0,threshold:n});
  let msg=Utilities.formatString('sum: %s maxidx: %s threshold: %s',obj.sum,obj.maxidx,obj.threshold);
  msg+='<br /><input type="text" id="nin" value="' + n + '" /> n<br />';
  msg+='<textarea id="Ain" rows="4" cols="60">' + A.join(",") +  '</textarea>A<br /><input type="button" value="Execute" onclick="runAgain();" />';
  msg+='<input type="button" value="Start Again From Scratch" onClick="google.script.run.stopWhenSumEqualsN();" />';
  msg+='<script>function runAgain(){let n=document.getElementById("nin").value;let A=document.getElementById("Ain").value.split(",");google.script.run.stopWhenSumEqualsN(n,A);}</script>'; 
  SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(msg), "Results");
}

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

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