[英]How can I make a sum of numbers in a for loop?
How can I make a for-loop which calculates the sum of all numbers from 1 to 100 and continuously stores it in sum.如何制作一个 for 循环来计算从 1 到 100 的所有数字的总和并将其连续存储在 sum 中。 That is the for loop must go from 1 to 100 inclusive?
那就是for循环必须go从1到100(含)?
let sum = 0; for (let i = 0; i <= 100; i++) { sum = sum + i; }
Your loop condition should be <
instead of >=
and within the loop you need to take the last value of sum
and add i
to it.您的循环条件应该是
<
而不是>=
并且在循环中您需要获取sum
的最后一个值并将i
添加到其中。 Lastly, if you want the sum of numbers from 1 to 100, then your loop has to start at 1 and end at 100.最后,如果您想要从 1 到 100 的数字总和,那么您的循环必须从 1 开始并以 100 结束。
let sum = 0; for (let i = 1; i < 101; i++) { sum = sum + i; } console.log(sum);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.