为什么以下两个代码给出不同的结果?第一个打印零,而第二个按预期打印随机计数。使用 gcc 4.6.3
8 int foo(){
9 return rand() % 2;
10 }
11
12 int main()
13 {
14 int ar[2] = {0};
15 for (int i = 0; i < 20; i++) {
16 // int tmp = foo();
17 // ar[tmp]++;
18 ar[foo()];
19 }
20
21 for (int i = 0; i < 2; i++)
22 cout << i << " : " << ar[i] << endl;
23 }
~~
_
8 int foo(){
9 return rand() % 2;
10 }
11
12 int main()
13 {
14 int ar[2] = {0};
15 for (int i = 0; i < 20; i++) {
16 int tmp = foo();
17 ar[tmp]++;
18 // ar[foo()];
19 }
20
21 for (int i = 0; i < 2; i++)
22 cout << i << " : " << ar[i] << endl;
23 }