vc++6.0中分别设计并实现阶乘和斐波那契的递归程序
时间: 2024-09-11 19:14:04 浏览: 70
C语言编程技术实践 函数嵌套调用和递归调用教学单元设计.doc
在Visual C++ 6.0中设计和实现阶乘和斐波那契数列的递归程序,首先我们需要理解这两个经典的递归函数:
1. **阶乘** (Factorial): 阶乘是一个正整数n的所有小于及等于它的正整数的积。递归定义为 n! = n * (n-1)!,当 n = 1 时基本情况。
```cpp
#include <iostream>
using namespace std;
int factorial(int n) {
if (n == 1 || n == 0)
return 1;
else
return n * factorial(n - 1);
}
int main() {
int num;
cout << "Enter a non-negative integer for factorial: ";
cin >> num;
cout << "Factorial of " << num << " is: " << factorial(num) << endl;
return 0;
}
```
2. **斐波那契数列** (Fibonacci sequence): 斐波那契数列是一个数列,每个数都是前两个数之和。递归形式为 F(n) = F(n-1) + F(n-2),基本情况通常取 F(0) = 0 和 F(1) = 1。
```cpp
#include <iostream>
using namespace std;
int fibonacci(int n) {
if (n <= 1)
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int num;
cout << "Enter a positive integer for Fibonacci sequence: ";
cin >> num;
cout << "Fibonacci number at position " << num << " is: " << fibonacci(num) << endl;
return 0;
}
```
阅读全文