一道小数学题,用for循环怎么去实现?

题目:计算从1开始的连续n个自然数之和,当其和值刚好超过100时结束,求n


代码:


var sum = 0;

var n = 0;

while(sum <= 100){

    n++;

    sum +=n;

}

console.log(sum);

console.log(n);

问题:这道题用for循环怎么实现呢?


波斯汪
浏览 484回答 8
8回答

幕布斯7119047

var sum = 0;&nbsp; &nbsp; for(var i = 0;i<=i;i++){&nbsp; &nbsp; &nbsp; &nbsp; if(sum >= 100){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sum += i;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; console.log('i =' +(i-1));&nbsp; //i = 14&nbsp; &nbsp; console.log('sum = '+sum); //sum = 105

隔江千里

function a(count){&nbsp; &nbsp; var sum =0;&nbsp; &nbsp; for(var i=1;i<count;i++){&nbsp; &nbsp; &nbsp; &nbsp; if(sum >count){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(i-1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; sum +=i;&nbsp; &nbsp; }}a(100);//求累加值刚好超过100,参数传100,求累加值刚好超过1000,参数传1000,

哈士奇WWW

var sum = 0;for (var i = 0; sum <= 100; i++) {&nbsp; &nbsp; sum += i;}console.log(sum);console.log(i-1);

杨__羊羊

function xx(){&nbsp; &nbsp; var sum=0;&nbsp; &nbsp; var n=0;&nbsp; &nbsp; for(;;){&nbsp; &nbsp; &nbsp; &nbsp; if(sum<=100){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; n++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sum+=n;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(n);&nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(n);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return n;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}xx();

蝴蝶刀刀

var sum = 0;for (var i = 1; sum <= 100; i++) {&nbsp; &nbsp; sum += i;}console.log(sum);console.log(i);

猛跑小猪

var a=1;var sum=0;while(sum<=100){&nbsp; &nbsp; a++;&nbsp; &nbsp; sum+=a;}console.log(sum);console.log(a);

Smart猫小萌

&nbsp; &nbsp; var n = 0;&nbsp; &nbsp; for(var i = 1; i<=100;i++){&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if(n<=100){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;n = i+n;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(n) //105&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(i);&nbsp; &nbsp; //14&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }

千巷猫影

function a(v) {&nbsp; &nbsp; for (let i = 0; i < i + 1; i++) {&nbsp; &nbsp; &nbsp; &nbsp; v -= i;&nbsp; &nbsp; &nbsp; &nbsp; if (v <= 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(i - 1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}a(100);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript