实验6-5 使用函数输出指定范围内的Fibonacci数 (20 分)
1. 题目摘自
https://pintia.cn/problem-sets/13/problems/477
2. 题目内容
本题要求实现一个计算Fibonacci数的简单函数,并利用其实现另一个函数,输出两正整数m和n(0<m≤n≤10000)之间的所有Fibonacci数。所谓Fibonacci数列就是满足任一项数字是前两项的和(最开始两项均定义为1)的数列。
函数接口定义:
int fib( int n );
void PrintFN( int m, int n );
其中函数fib须返回第n项Fibonacci数;函数PrintFN要在一行中输出给定范围[m, n]内的所有Fibonacci数,相邻数字间有一个空格,行末不得有多余空格。如果给定区间内没有Fibonacci数,则输出一行“No Fibonacci number”。
输入样例1:
20 100 7
输出样例1:
fib(7) = 13
21 34 55 89
输入样例2:
2000 2500 8
输出样例2:
fib(8) = 21
No Fibonacci number
3. 源码参考
#include <iostream>
using namespace std;
int fib( int n );
void PrintFN( int m, int n );
int main()
{
int m, n, t;
cin >> m >> n >> t;
cout << "fib(" << t << ") = " << fib(t) << endl;
PrintFN(m, n);
return 0;
}
int fib( int n )
{
if(n < 0)
{
return 0;
}
else if((n == 1) || (n == 2))
{
return 1;
}
else
{
return fib(n - 1) + fib(n - 2);
}
}
void PrintFN( int m, int n )
{
int a, b;
a = b = 0;
while(fib(a) < m)
{
a++;
}
while(fib(b) < n)
{
b++;
}
if(fib(b) > n)
{
b--;
}
if((a >= 1) && (a <= b))
{
cout << fib(a);
for(int i = a + 1; i <= b; i++)
{
cout << " " << fib(i);
}
cout << endl;
}
else
{
cout << "No Fibonacci number" << endl;
}
return;
}