First, a solution using addition is written in the header file whichfibonaccinumber.h . There is no verification that the input number is less than 0.
#ifndef whichfibonaccinumber_h_#define whichfibonaccinumber_h_typedef unsigned long long uint64;//abbreviated unsigned long long , because it is 64 bits, writing UInt64 (meaning: Unsigned int 64 bit)//max = = 18446744073709551615, try to ensure that no overflow. Another: the "General formula" solution needs to open square. UInt64 whichfibonaccinumber (int numbers) { if (1 = = Number | | 2 = #) { return 1;//sequence number is 1 and 2 Fibonacci is 1, return 1< c4/>} Else { UInt64 prev = 1;//Previous number UInt64 next = 1;//after a number uint64 result = prev + next;//final return results, first two Number add int index = 3;//number of Fibonacci numbers, 3rd is 2 while (number! = index)//check ordinal { prev = next; Next = result; Result + = prev;//more than 3 lines to do is to update the number, and to calculate the new number ++index;//new number of the ordinal } return result;//return the result }} #endif// Whichfibonaccinumber
Then the main program main.cpp, using a loop to continuously enter the sequence number. The validation of the input sequence number is also done here.
#include <iostream> #include "whichfibonaccinumber.h" int main () { using Std::cout; Using Std::cin; Using Std::endl; unsigned long long and 8 bytes 64 bits cout << "number of Fibonacci numbers:"; int index; while (CIN >> index) { if (index <= 0) { cout << "ordinal cannot be less than 1" << Endl; Continue; } cout << "<< index <<" Fibonacci numbers are: "; cout << whichfibonaccinumber (index) << Endl; cout << "continue to seek the first few Fibonacci numbers, or enter any non-numeric characters to exit:"; } return 0;}
Impression: Neglect The basic knowledge, do not do well today. For I have not entered the training institutions, the interview unit will pay more attention to the basis of the test.
"C + +", "Fibonacci", seek the first few Fibonacci numbers.