Variabel每次给出一个看似随机的答案

时间:2016-11-29 19:13:59

标签: c++ debugging random integer

我正在学习C ++并尝试使用Project Euler(问题2)来练习我的C ++能力。一切都编译得很好,但每次定义某个变量时,它都会以一个看似随机的整数开始。这是代码:

#include <iostream>
#include <Windows.h>

int fibonacci(int tripoloski){
    int first = 1;
    int second = 1;
    int next;
    int result;
    std::cout << first << std::endl;
    std::cout << second << std::endl;
    for(next = 1; next < tripoloski; ){
        result = result + first + second;
        next = first + second;
        first = second;
        second = next;
        std::cout << next << std::endl;
        std::cout << "WHOOP: " << result << std::endl;
    }
    return result;
}

int main(){
    int a = fibonacci(4000000);
    std::cout << "RESULT: " << a << std::endl;
    system("pause");
    return 0;
}

这是一个输出日志(忽略&#34; tripoloski&#34;和#34; WHOOP&#34; :)):

1
1
2
WHOOP: 1075637419
3
WHOOP: 1075637422
5
WHOOP: 1075637427
8
WHOOP: 1075637435
13
WHOOP: 1075637448
21
WHOOP: 1075637469
34
WHOOP: 1075637503
55
WHOOP: 1075637558
89
WHOOP: 1075637647
144
WHOOP: 1075637791
233
WHOOP: 1075638024
377
WHOOP: 1075638401
610
WHOOP: 1075639011
987
WHOOP: 1075639998
1597
WHOOP: 1075641595
2584
WHOOP: 1075644179
4181
WHOOP: 1075648360
6765
WHOOP: 1075655125
10946
WHOOP: 1075666071
17711
WHOOP: 1075683782
28657
WHOOP: 1075712439
46368
WHOOP: 1075758807
75025
WHOOP: 1075833832
121393
WHOOP: 1075955225
196418
WHOOP: 1076151643
317811
WHOOP: 1076469454
514229
WHOOP: 1076983683
832040
WHOOP: 1077815723
1346269
WHOOP: 1079161992
2178309
WHOOP: 1081340301
3524578
WHOOP: 1084864879
5702887
WHOOP: 1090567766
RESULT: 1090567766
Press any key to continue . . .

第二个输出日志......:

1
1
2
WHOOP: 702745584
3
WHOOP: 702745587
5
WHOOP: 702745592
8
WHOOP: 702745600
13
WHOOP: 702745613
21
WHOOP: 702745634
34
WHOOP: 702745668
55
WHOOP: 702745723
89
WHOOP: 702745812
144
WHOOP: 702745956
233
WHOOP: 702746189
377
WHOOP: 702746566
610
WHOOP: 702747176
987
WHOOP: 702748163
1597
WHOOP: 702749760
2584
WHOOP: 702752344
4181
WHOOP: 702756525
6765
WHOOP: 702763290
10946
WHOOP: 702774236
17711
WHOOP: 702791947
28657
WHOOP: 702820604
46368
WHOOP: 702866972
75025
WHOOP: 702941997
121393
WHOOP: 703063390
196418
WHOOP: 703259808
317811
WHOOP: 703577619
514229
WHOOP: 704091848
832040
WHOOP: 704923888
1346269
WHOOP: 706270157
2178309
WHOOP: 708448466
3524578
WHOOP: 711973044
5702887
WHOOP: 717675931
RESULT: 717675931
Press any key to continue . . .

正如我之前所说,我刚开始学习C ++(大约几天前),所以答案可能对你来说非常明显。如果你不是因为它而抨击我,我会很感激,并给我一个有见地的解释:)

-ThomThom

2 个答案:

答案 0 :(得分:4)

当您编写result = result + first + second;时,您尚未在此之前初始化变量result。这是undefined behavior,此时变量可以包含任何内容。在此处使用变量之前将变量初始化为0将解决问题。

答案 1 :(得分:2)

永远不会初始化result变量。尝试将其声明更改为int result = 0

相关问题