输出 Fibonacci 序列(使用函数)

| October 26, 2007 14:44 | timmy | Via Original
输入一个正整数repeat (0输入2 个正整数m和n(1<=m,n<=10000),输出m 和n之间所有的Fibonacci数。
Fibonacci 序列(第1项起):1  1  2  3  5  8  13  21 ......
要求定义并调用函数fib(n),它的功能是返回第n项Fibonacci数。例如,fib(7)的返回值是13。
输出语句:printf("%ld ", f);

例:括号内是说明
输入:
3      (repeat=3)
1 10   (m=1, n=10)
20 100  (m=20, n=100)
1000 6000  (m=1000, n=6000)
输出:
1 1 2 3 5 8        (1到10之间的Fibonacci数)
21  34  55  89     (20到100之间的Fibonacci数)
1597  2584  4181   (1000到6000之间的Fibonacci数)


#include "stdio.h"
#include "math.h"
int main( )
{
 int ri,repeat;
 int i,m,n;
 long f;
 long fib(int n);

 scanf("%d",&repeat);
 for(ri=1;ri<=repeat;ri++){
   scanf("%d%d", &m, &n);
  i=1;
  while(fib(i)<=n){
    f=fib(i);
    if(f>=m) printf("%ld ", f);  
    i++;
  }
 printf("\n");
 }
}

long fib(int n)
{
 int i,x1,x2,x;
 if(n==1||n==2)
   x=1;
 else{    
   x1=x2=1;
   for(i=1;i<=n-2;i++){
     x=x1+x2;
     x1=x2;
     x2=x;
   }
 }
 return x;
}
Tags:
Program/Code » C/C++ | Comments(0) | Trackbacks(0) | Reads(375)
Add a comment
 Site URI
 Email
  Password Optional
 Nickname  *  [Register]
               

 
Emots
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
Enable HTML
Enable UBB
Enable Emots
Hidden
Remember