欧拉项目练习题吧: 题目002

/*
Each new term in the Fibonacci sequence is generated by adding the previous two
terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the even-valued terms.
*/

#include <assert.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

#define CEILING 4000000

int sum_fib_even ( const int );

int main( void )
{
  printf ( "Sum of the even-valued terms is %d\n" ,
             sum_fib_even ( CEILING )  ) ;
           
  system("PAUSE"); 
  return 0;
}

int sum_fib_even ( const int ceiling )
{
    int fib_term0 = 0 , fib_term1 = 1 , fib_term2 = 2 ;
    int sum_even  = 0 ;   
   
    while ( fib_term2 <= ceiling) {
          assert ( INT_MAX - sum_even >= fib_term2 ) ;//实在很不放心
          sum_even += fib_term2 ;
         
          fib_term0 = fib_term1 + fib_term2 ;
          fib_term1 = fib_term2 + fib_term0 ;
          fib_term2 = fib_term0 + fib_term1 ;   
    }
   
    return sum_even ;
}

参考博文:

http://www.cnblogs.com/zhouyinhui/archive/2011/01/06/1929153.html

原文地址:https://www.cnblogs.com/KBTiller/p/1974738.html