为什么我的代码有效?简单的算术
Why does my code work? Simple arithmetics
我正在编写一个简单的代码来计算法波那契数作为练习。代码有效,但我不明白为什么。我有一些特殊情况n=1
和n=2
这是数字在序列中的位置(数字是 0 和 1(。但是,在这些之后,将在此循环中计算数字。
while(n>LoopCount)
{
Fib_n=Fib_1+Fib_2;
Fib_2=Fib_1;
Fib_1=Fib_n;
LoopCount++;
}
进入循环,Fib_1=0
、Fib_2=0
和Fib_n=1
。为什么这个循环无论如何都不直接吐出0
?整个代码如下。
#include <iostream>
using namespace std;
int main()
{
cout <<"Which number of the Fibonacci sequence do you want to calculate?" <<endl;
int n;
cin >>n;
cout <<endl;
int Fib_n;
int Fib_1;
int Fib_2;
int LoopCount=1;
if(n>1)
{
Fib_n=1;
LoopCount++;
while(n>LoopCount)
{
Fib_n=Fib_1+Fib_2;
Fib_2=Fib_1;
Fib_1=Fib_n;
LoopCount++;
}
}
cout <<Fib_n;
return 0;
}
int Fib_1;
int Fib_2;
从未初始化。因此,第一次计算Fib_n=Fib_1+Fib_2;
时,Fib_n
将得到两个未初始化变量的总和。
我已经修改了您的代码,以便它可以工作。
#include <iostream>
using namespace std;
int main()
{
cout <<"Which number of the Fibonacci sequence do you want to calculate?" <<endl;
int n;
cin >> n;
cout << endl;
int Fib_1 = 1;
int Fib_2 = 1;
int count = 0;
while(n > count)
{
Fib_1 = Fib_1 + Fib_2;
Fib_2 = Fib_1 - Fib_2;
count++;
}
cout << Fib_1;
return 0;
}
Fib_1
您将其作为非初始变量,因此您可能会获得输出的垃圾值。
Fib_2 = Fib_1
接下来,使用 Fib_1
初始化Fib_2
,这意味着它们都共享相同的(随机(值。
在调试模式下,它们都初始化为 0,并添加它们:
Fib_n=Fib_1+Fib_2;
使总和等于 0。在发布模式下,你可以期待来自编译器的随机值。下面是有关未初始化变量的详细信息。
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 查找定义我的 C/C++ 函数/宏的文件比'grep'更简单的方法
- 我怎样才能简单地将opencv 包含在我的项目中与CMake
- 运行简单的.oct文件时Octave崩溃,我的代码出了什么问题?
- 在我的第一个C++程序中需要一些帮助(简单)
- C++:我的简单计算器程序无法打印出来。我也认为我的变量命名不正确
- 为什么叮当使我的简单阶乘函数过于复杂
- 为什么我的简单C++程序使用队列和 fstream 错误到无效指针
- 为什么我的简单代码在C++中不起作用?
- 如何简单地管理我的游戏状态?C++
- 在一个简单的高峰时间求解器中使用BFS——为什么我的代码不能求解棋盘
- 为什么我的程序的这个简单部分使我打了两个多小时
- C++简单的程序 - 为什么我的"res"不进入我的向量?创建一个接受输入 (4+44-67+235) 并输出结果的程序
- 为什么对于简单的 StereoBM 算法,我的代码比 opencv 慢得多
- 为什么我的简单C++项目在我可以看到之前就终止于日食?我如何让它停止
- 简单程序没有输出和崩溃.我的解决方案有什么问题
- 简单的Thrust代码的执行速度大约是我的cuda内核的一半.我用Thrust错了吗
- 将我的简单winsock服务器/客户端应用程序变形为简单的Web服务器
- 在我的Mac OSX El Capitan上编译带有意外错误的简单C++类
- 我无法让我的简单程序将 2D 数组传递给函数