我正在尝试获取并打印填充if
条件的所有值的总和,但到目前为止还没有成功。
另外,有没有办法用最大值(例如999999)分隔fib()
,而不是通过numMax
操作分隔它?
fib = function(numMax) {
for (i = 0, j = 1, k = 0; k < numMax; i = j, j = x, k++) {
x = i + j;
if (x % 2 === 0) {
sum += x;
console.log(x);
}
}
};
fib(32);
答案 0 :(得分:1)
您的函数可以return
一个值,您可以将其存储在变量中:
fib = function(numMax){
var sum = 0;
for(i=0,j=1,k=0; k<numMax;i=j,j=x,k++ ){
var x = i + j;
if (x % 2 === 0){
sum += x; // This is the same like sum = sum + x;
}
}
return sum; // Let's return the calculated sum as the result of the function
};
var result = fib(32); // result contains the value the function returned
console.log(result);
我不确定你问题的第二部分。你想要,numMax不能大于999999吗?
fib = function(numMax){
if (numMax > 999999) {
numMax = 999999;
}
var sum = 0;
for(i = 0, j = 1, k = 0; k < numMax; i = j, j = x, k++){
var x = i + j;
if (x % 2 === 0){
sum += x; // This is the same like sum = sum + x;
}
}
return sum; // Let's return the calculated sum as the result of the function
};
var result = fib(32); // result contains the value the function returned
console.log(result);