当我期望1时,c ++ int变为4198321左右

时间:2017-07-26 11:30:24

标签: c++ int

我是c ++的新手,但是我已经深入了解了python和c#,我不记得这样的事情发生了。我试图计算一个数组中有多少正,负和零,但计数以某种方式跳到4198321左右,但它略有不同。那么为什么会发生这种情况以及导致它发生的原因呢?我无法在网上找到任何答案。 代码:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main()
{
    long n, pos, neg, zer;
    cin >> n;
    vector<int> arr(n);
    for(int arr_i = 0;arr_i < n;arr_i++){
       cin >> arr[arr_i];
    }
    for(int i; i < n; i++)
    {
        if(arr[i] > 0)
        {
            pos++;
            cout << "pos now is: " << pos << endl;
        }
        else if(arr[i] < 0)
        {
            neg++;
            cout << "neg now is: " << pos << endl;
        }
        else if(arr[i] == 0)
        {
            zer++;
            cout << "zer now is: " << pos << endl;
        }
    }
    cout << "pos: " << pos << endl;
    cout << "neg: " << neg << endl;
    cout << "zer: " << zer << endl;

    return 0;
}

很抱歉,如果我花了太长时间才能达到目的,这是我提出的第一个问题。输出(如果需要)是:

neg now is: 4198320
pos now is: 4198321
neg now is: 4198321
zer now is: 4198321
pos now is: 4198322
pos now is: 4198323
pos: 4198323
neg: 4
zer: 1

2 个答案:

答案 0 :(得分:0)

for(int i; i < n; i++)中,变量i未初始化。

其余的是未定义的行为。

答案 1 :(得分:0)

您可以尝试的最简单的事情是在计算数字之前打印pos 。这应该是零,但你实际上并没有将pos设置为零。你得到了一些随机值,无论之前的内存位置是什么。

从形式上讲,这是Undefined Behavior,结果可能会得到"lemon"