如何用JavaScript的for/while循环迭代到100并显示每次迭代的累计和
实现思路
- 需要两个累加变量:
currentSum记录单次迭代中1到n的和,totalSum记录所有单次和的总累计值,用来判断是否满足总累计和 <= 100的终止条件 - 每次迭代生成
1+2+…+n格式的表达式字符串,按示例格式输出即可
可直接运行的实现代码
let currentSum = 0; let totalSum = 0; let iterationNum = 1; // 循环直到总累计和超过100就终止 while (true) { currentSum += iterationNum; // 预计算加完当前项后是否超过阈值,超过直接退出 if (totalSum + currentSum > 100) { break; } totalSum += currentSum; // 生成类似 1+2+3 的表达式字符串 const expression = Array.from({length: iterationNum}, (_, idx) => idx + 1).join('+'); // 按要求格式输出 console.log(`Iteracion${iterationNum}: ${expression} = ${currentSum}`); iterationNum++; }
运行输出结果
Iteracion1: 1 = 1 Iteracion2: 1+2 = 3 Iteracion3: 1+2+3 = 6 Iteracion4: 1+2+3+4 = 10 Iteracion5: 1+2+3+4+5 = 15 Iteracion6: 1+2+3+4+5+6 = 21 Iteracion7: 1+2+3+4+5+6+7 = 28
*注:输出到第7次时总累计和为84,再加第8次的单次和36后总累计为120,超过100阈值,因此循环终止。
内容的提问来源于stack exchange,提问作者Ruben
相关产品推荐
相关产品推荐

