int数组给疯狂的值,除非所有领域initalized为0,为什么呢? [英] int array gives crazy values unless all fields initalized to 0, why?

查看:232
本文介绍了int数组给疯狂的值,除非所有领域initalized为0,为什么呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int TwoThrows();


int main(){

        int Throws, Throw, Frequency[13]={0,0,0,0,0,0,0,0,0,0,0,0,0};
        randomize();


        cout << "\nThis program simulates throws of two dice.";
        cout << "\n\nHow many throws : ";
        cin >> Throws;



        // Calls TwoThrows and saves in Frequency by value
        for(int I=0; I<Throws; I++){
                Throw=TwoThrows();   //2-12
                Frequency[Throw]++;   //2-12

        }

         // Prints array:
        for(int I=0; I<11; I++){
                cout << I+2 << ":\t" << Frequency[I+2] << "\n";

        }

        return 0;
}

int TwoThrows(){
        unsigned int I=(random(6)+1)+(random(6)+1);

        return I;

}

这将打印:

2:1317
3:2724
4:4145
5:5513
6:7056
7:8343
8:6982
9:5580
10:4176
11:2776
12:1388

2: 1317 3: 2724 4: 4145 5: 5513 6: 7056 7: 8343 8: 6982 9: 5580 10: 4176 11: 2776 12: 1388

这是伟大的。

不过,我想知道的是,我为什么要设置阵列{} 0,0,0,0,0,0,0,0,0,0,0,0,0?

However, what I want to know is, why did I have to set the array to {0,0,0,0,0,0,0,0,0,0,0,0,0}?

如果我不这样做;我得到:

If I do NOT do that; i get:

2:30626868
3:1638233
4:844545295
5:1
6:9
7:4202510
8:4199197
9:844555757
10:3
11:4202574
12:2130567168

2: 30626868 3: 1638233 4: 844545295 5: 1 6: 9 7: 4202510 8: 4199197 9: 844555757 10: 3 11: 4202574 12: 2130567168

推荐答案

如果你不初始化数组,然后继续增加它的元素,在技术上这是的未定义行为

If you don't initialize the array, and then proceed to increment its elements, technically this is undefined behaviour.

会发生什么事在实践中,数组的元素得到任何值正好是在栈上时,的main()开始。

What happens in practice is that the array's elements get whatever values happen to be on the stack when main() starts.

这篇关于int数组给疯狂的值,除非所有领域initalized为0,为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆