生成金字塔斐波那契数列c++
时间: 2024-04-19 12:20:39 浏览: 78
c++实现斐波那契数列
以下是生成金字塔和斐波那契数列的C++代码示例:
生成金字塔:
```cpp
#include <iostream>
using namespace std;
int main() {
int count = 0;
cout << "请输入要打印多少层:";
cin >> count;
for (int i = 1; i < count; i++) {
// 打印空格
for (int j = 0; j < count - i; j++) {
cout << " "; }
// 打印*
for (int k = 0; k <= i * 2 - 1; k++) {
cout << "*";
}
cout << endl;
}
return 0;
}
```
生成斐波那契数列:
```cpp
#include <iostream>
using namespace std;
int fibonacci(int n) {
if (n <= 1) {
return n;
}
int a = 0, b = 1, c;
for (int i = 2; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return b;
}
int main() {
int n;
cout << "请输入要计算第几个斐波那契数:";
cin >> n;
int result = fibonacci(n);
cout << "第" << n << "个斐波那契数是:" << result << endl;
return 0;
}
```
阅读全文