[英]Write a function sumRange, which, when given two integers FROM and TO, returns the sum of integers from FROM to TO
Could anyone please tell me how I could write this code better, I'm having a bit of trouble getting mine to work 任何人都可以告诉我如何更好地编写此代码,让我上班有点麻烦
function sumRange(from, to) {
var f = from;
var t = to;
var result = from;
if(to >= from) {
while (to > from) {
from ++;
result += from;
}
return result;
} else if (from > to) {
result = to;
while (from > to ) {
to++;
result += to;
}
return result;
}
}
The sum of the integers between a
and b
is: a
和b
之间的整数之和为:
((b - a + 1) * (a + b)) / 2
See http://mathworld.wolfram.com/ArithmeticSeries.html 参见http://mathworld.wolfram.com/ArithmeticSeries.html
To handle the arguments in any order: 要以任何顺序处理参数:
function sumRange(a, b) {
return ((Math.abs(b - a) + 1) * (a + b)) / 2;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.