[英]Fibonacci number
i am writing code that prints determined by user fibonacci number. 我正在编写由用户斐波那契数确定的打印代码。 The problem is that when i type 0, or 1 everything run as i expect whereas as i type 3 or more output of the program is random number(location of result variable in computer memory), please excause me for such easy question, but at work i am coding in VBA, and after switching to C++ i cannot see what is wrong with my code, and i have no one to ask for help because i am self-lerner.
问题是,当我键入0或1时,所有内容都按预期运行,而当我键入3或以上时,程序的输出为随机数(结果变量在计算机内存中的位置),请问问我这样简单的问题,但是在我正在用VBA进行编码,在切换到C ++之后我看不到我的代码出了什么问题,并且由于我是一个自我学习者,我没有人要寻求帮助。 Big thanks in advance.
预先感谢。
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int f0, f1, a, result;
f0 = 0;
f1 = 1;
cout << "Type number of fibonacci element you want to print\n" << endl;
cin >> a;
if (a == 0)
{
result = f0;
cout << "Your result it;\n";
cout << result;
}
if (a == 1)
{
result = f1;
cout << "Your result is";
cout << result;
}
if (a >= 2)
{
for (int i = 2; i > a; i++)
result = f0 + f1;
f0 = f1;
f1 = result;
cout << "Your result is:\n";
cout << result;
}
return 0;
}
for(int i=2;i>a;i++)
result = f0+f1;
f0 = f1;
f1 = result;
Instead this should be like that: 而是应该像这样:
for(int i=2;i<=a;i++){
result = f0+f1;
f0 = f1;
f1 = result;
}
So, firstly: correct use brackets, and secondly: i<=a
in place of (i>a)
. 因此,首先:正确使用括号,其次:
i<=a
代替(i>a)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.