为什么我的代码有效?简单的算术

Why does my code work? Simple arithmetics

本文关键字:简单 我的 代码 有效 为什么      更新时间:2023-10-16

我正在编写一个简单的代码来计算法波那契数作为练习。代码有效,但我不明白为什么。我有一些特殊情况n=1n=2这是数字在序列中的位置(数字是 0 和 1(。但是,在这些之后,将在此循环中计算数字。

while(n>LoopCount)
{
    Fib_n=Fib_1+Fib_2;
    Fib_2=Fib_1;
    Fib_1=Fib_n;
    LoopCount++;
}

进入循环,Fib_1=0Fib_2=0Fib_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。在发布模式下,你可以期待来自编译器的随机值。下面是有关未初始化变量的详细信息。

相关文章: