编写程序,定义函数void fib(int n)计算斐波那锲数列。在主函数中输出前20个数,并利用输入流读取本程序,将源代码在屏幕逐行输出。
时间: 2023-04-18 11:00:47 浏览: 54
好的,以下是程序的中文回复:
程序如下:
#include <iostream>
using namespace std;
void fib(int n) {
int a = , b = 1, c;
for (int i = ; i < n; i++) {
cout << a << " ";
c = a + b;
a = b;
b = c;
}
}
int main() {
fib(20);
cout << endl;
ifstream fin("fib.cpp");
string line;
while (getline(fin, line)) {
cout << line << endl;
}
fin.close();
return ;
}
其中,fib函数用于计算斐波那契数列,参数n表示要计算的数列长度。在主函数中,我们先调用fib函数输出前20个斐波那契数列的数值,然后利用输入流读取程序源代码,逐行输出到屏幕上。
注意,为了使用输入流读取源代码,我们需要在程序开头添加以下头文件:
#include <fstream>
并在读取完毕后关闭文件流:
fin.close();
希望这个回复能够帮到你,有任何问题欢迎继续提问。
相关问题
2. 编写程序,定义函数void fib(int n)计算斐波那锲数列。在主函数中输出前20个数,并利用输入流读取本程序,将源代码在屏幕逐行输出。
以下是程序代码:
#include <iostream>
using namespace std;
void fib(int n) {
int a = , b = 1, c;
for (int i = 1; i <= n; i++) {
cout << a << " ";
c = a + b;
a = b;
b = c;
}
}
int main() {
fib(20);
// 读取本程序并逐行输出
string line;
ifstream file("fibonacci.cpp");
if (file.is_open()) {
while (getline(file, line)) {
cout << line << endl;
}
file.close();
}
else {
cout << "无法打开文件" << endl;
}
return ;
}
定义递归函数求Fib(n),并在主函数中调用Fib(n),输出数列的前30项,每输出5个数换行。
好的,以下是递归函数求Fib(n)的代码,并在主函数中输出数列的前30项。
```python
def Fib(n):
if n <= 1:
return n
else:
return Fib(n-1) + Fib(n-2)
for i in range(30):
print(Fib(i), end=' ')
if (i+1) % 5 == 0:
print()
```
输出结果为:
```
0 1 1 2 3
5 8 13 21 34
55 89 144 233 377
610 987 1597 2584 4181
6765 10946 17711 28657 46368
```