English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
다음은 재귀를 사용한 피보나치 수열의 예제입니다.
#include <iostream> using namespace std; int fib(int x) { if((x ==1) || (x == 0)) { return(x); } else { return(fib(x-1)+fib(x-2)); } } int main() { int x, i = 0; cout << "Enter the number of terms of series : "; cin >> x; cout << "\nFibonnaci 시리즈 : "; while(i < x) { cout << " " << fib(i); i++; } return 0; }
출력 결과
Enter the number of terms of series : 15 Fibonnaci 시리즈 : 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
위의 프로그램에서 실제 코드는 함수 "fib"에 있습니다. 다음과 같습니다:
if((x ==1) || (x == 0)) { return(x); } else { return(fib(x-1)+fib(x-2)); }
이main()
메서드에서, 사용자 입력을fib()
여러 표현식을 호출했습니다. 다음과 같이 피보나치 시리즈를 출력합니다.
cout << "Enter the number of terms of series : "; cin >> x; cout << "\nFibonnaci 시리즈 : "; while(i < x) { cout << " " << fib(i); i++; }