计算斐波那契函数前200项的平均值问题
做一个纯纯的文科生,竟然报了程序设计这门课,更坑爹的是总共才上了三节课,就出了这么一道题“计算斐波那契数列前200项的平均值。”好晕啊,根本不知道从何处下手,求大神帮助啊
#include <stdio.h> #include <math.h> double fibonacci_approximately( unsigned n ) { double s5 = sqrt(5.0); return ( pow((1+s5)/2,n+0.0)-pow((1-s5)/2,n+0.0) )/s5; } void fibonacci( unsigned n, unsigned a[5] ) { unsigned b[5]={1}; a[0]=0,a[1]=0,a[2]=0,a[3]=0,a[4]=0; while( n-- ) { unsigned carry = 0; for( size_t i=0; i!=5; ++i ) { carry += a[i] + b[i]; a[i] = b[i]; b[i] = carry%1000000000; carry /= 1000000000; } } } int main( void ) { const unsigned n = 200; printf( "斐波那契数列第%u项 约为 %lg\n", n+2, fibonacci_approximately(n+2) ); unsigned r[5]; fibonacci( n+2, r ); printf( "斐波那契数列第%u项 等于 %u%09u%09u%09u%09u\n", n+2, r[4],r[3],r[2],r[1],r[0] );这样就算出斐波那契数列第202项
#include <stdio.h> // s(n) = s(n-2) + s(n-1) + 1; s(-1)=0, s(0)=0 void fibonacci_avg( unsigned n ) { // 斐波那契数列前n项之和 unsigned a[6]={0}, b[6]={0}; for( unsigned m=0; m!=n; ++m ) { unsigned carry = 1; for( size_t i=0; i!=6; ++i ) { carry += a[i] + b[i]; a[i] = b[i]; b[i] = carry%10000000; carry /= 10000000; } } // 平均值 unsigned carry = 0; for( size_t i=0; i!=6; ++i ) { carry = carry*10000000 + b[5-i]; a[i] = carry/n; carry %= n; } // 十进制输出 printf( "%u%07u%07u%07u%07u%06u%g\n", a[0],a[1],a[2],a[3],a[4],a[5]/10,a[5]%10+carry*1.0/n ); return; } int main( void ) { fibonacci_avg( 200 ); return 0; }输出