pta Zhejiang University Edition "C Language Programming (3rd Edition)" Exercise 6-4 Use a function to output Fibonacci numbers within a specified range (20 points)

C language

 

 

This question requires the realization of a simple function for calculating Fibonacci numbers, and using it to implement another function, outputting all Fibonacci numbers between two positive integers m and n (0<m≤n≤10000). The so-called Fibonacci sequence is a sequence that satisfies that any number is the sum of the first two terms (the first two terms are both defined as 1).

Function interface definition:

int fib( int n );
void PrintFN( int m, int n );

 

The function fibmust return the nFibonacci number; the function PrintFNshould output all Fibonacci numbers in the given range [ m, n] in one line, with a space between adjacent numbers, and no extra space at the end of the line. If there is no Fibonacci number in the given interval, output a line of "No Fibonacci number".

Sample referee test procedure:

#include <stdio.h>

int fib( int n );
void PrintFN( int m, int n );
	
int main()
{
    int m, n, t;

    scanf("%d %d %d", &m, &n, &t);
    printf("fib(%d) = %d\n", t, fib(t));
    PrintFN(m, n);

    return 0;
}

/* 你的代码将被嵌在这里 */

 

Input example 1:

20 100 7

 

Sample output 1:

fib(7) = 13
21 34 55 89

 

Input example 2:

2000 2500 8

 

Output sample 2:

fib(8) = 21
No Fibonacci number

int fib( int n )
{    
    int sum;
    if(n==1||n==2)
       return 1;
    else
    {
      sum=fib(n-1)+fib(n-2);
      return sum;
    }
  
}
void PrintFN( int m, int n )
{
   int flag=0,i=1,count;

      while(fib(i)<m)//Find the fib number greater than or equal to m
        i++;
 
     count=i;//count is the subscript of the first fid number greater than or equal to m (the i-th fib number)
  
     while(fib (i)<=n)//Find the fib number greater than n and its subscript
        i++;
      while(count<i)
      {          if(fib(count)>=m&&fib(count)<=n&&flag==1)//space Before putting, make sure that there are no extra spaces in the result             printf("%d",fib(count));

     if(fib(count)>=m&&fib(count)<=n&&flag==0)//output the first number without spaces after it
          {             printf("%d",fib(count));             flag=1;           }        count++ ;       }   if(flag==0)//Judging whether there is a Fibonacci number     printf("No Fibonacci number");   printf("\n"); }








  
    

Note: 1. The last test point: there is only one 1, test fib(2), it can be understood as m=n=1, but the value of fib(1), fib(2) should be output (that is, 1 1) ;
    2. If you have any questions, please leave a message for correction, thank you for your suggestion;
    3. If there is a better way, please leave a message.

 

Guess you like

Origin blog.csdn.net/L_Z_jay/article/details/106031386