Closed. This question needs details or clarity。它当前不接受答案。
                        
                    
                
            
        
            
        
                
                    
                
            
                
                    想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
                
                    4年前关闭。
            
        

    

我正在尝试获取并打印满足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);

最佳答案

您的函数可以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);

07-24 21:32