我正在尝试使用 JavaScript 为“确定需要添加多少个整数,从数字 1 开始,使总和大于 100”这一任务找到解决方案。 我有我的解决方案,但我倾向于认为这是错误的。 你能帮帮我吗?
我什至没有意识到我是否以正确的方式理解了任务。 请在下面查看我的解决方案:
<script>
let result = 0;
for ( i = 1; i<20; i++){
result+=i;
if( result>100) {
break
}
}
console.log(i)
</script>
输出是14,是对的,但我不确定我的解法。
最佳答案
如果有效,就没有问题。
您可以简化它,例如使用 while
而不是 for
循环:
let total = 0
let count = 1;
// we loop until total is greater or equals to 100.
while(total < 100) {
// add the current count to the total
total += count;
// increment the count.
count++;
}
// we need to account for the last ++;
console.log(count - 1);
此处 while
循环将运行直到条件被打破。
关于javascript - 从数字 1 开始,确定需要添加多少个整数才能使总和大于 100?使用 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58525351/