斐波那契数列c++while
时间: 2023-11-26 08:06:39 浏览: 138
C++ 斐波那契数列
以下是使用C++ while循环实现斐波那契数列的代码:
```c++
#include <iostream>
using namespace std;
int main() {
int n;
cout << "请输入要求的斐波那契数列的项数:";
cin >> n;
int f0 = 0, f1 = 1, f2;
cout << "斐波那契数列前" << n << "项为:";
if (n >= 1) {
cout << f0 << " ";
}
if (n >= 2) {
cout << f1 << " ";
}
for (int i = 3; i <= n; i++) {
f2 = f0 + f1;
cout << f2 << " ";
f0 = f1;
f1 = f2;
}
cout << endl;
return 0;
}
```
阅读全文