简体   繁体   English

如何在for循环中使用负值

[英]how to use negative values in for loops

i am trying to get the sum of odd numbers with values starting from -300,000 to 300,000 and i am getting my result as ZERO can anybody help why?我试图得到值从 -300,000 到 300,000 的奇数的总和,我得到的结果为零,有人可以帮忙吗?

var sum=0;
for(var i= -300000;i<=300000;i++){
    if(i%2!==0){
        sum=sum+i
    }
}
console.log(sum);

what is wrong with my code我的代码有什么问题

Try this simplified code (with a bit a debug) to understand that there's just a math issue :试试这个简化的代码(有一点调试)以了解这只是一个数学问题:

for (var i= -30;i<=30;i++){
    console.log('i == ' + i);
    if (i%2!==0) {
        sum+=i;
        console.log('sum is now ' + sum);
    }
}

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

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