C ++中的斐波那契数列 [英] Fibonacci series in C++
本文介绍了C ++中的斐波那契数列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include <iostream>
using namespace std;
int main()
{
int num1 = 0;
int num2 = 1;
int num_temp;
int num_next = 1;
int n;
cin >> n;
for (int i = 0; i < n; i++){
cout << num_next << " ";
num_next = num1 + num2;
num1 = num2;
num_temp = num2;
num2 = num_next - num1;
num1 = num_temp;
}
return 0;
}
我必须输出第一个"n"斐波那契数,但是我认为逻辑上有问题.前3或4个元素是正确的,但随后出现问题...
I have to output the first "n" fibonacci numbers however I think there is some problem in logic.. I can't find out what am I doing wrong. The first 3 or 4 elements are correct but then a problem occurs...
预期:
对于 n = 9
0、1、1、2、3、5、8、13、21
0, 1, 1, 2, 3, 5, 8, 13, 21
实际:
1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
推荐答案
#include <iostream>
using namespace std;
int main()
{
int num1 = 0;
int num2 = 1;
int num_temp;
int num_next = 1;
int n;
cin >> n;
if (n>=1)
cout << 0 << " ";
if (n>=2)
cout << 1 << " ";
for (int i = 0; i < n-2; i++){
num_next = num1 + num2;
cout << num_next << " ";
num1 = num2;
num2 = num_next;
}
cout << endl;
return 0;
}
这篇关于C ++中的斐波那契数列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文