random number generator: Keep track of certain numbers

Nov 16, 2014 at 8:26pm
Hello,
I am writing a program that generates random numbers with in the range [0,2].
I want to keep track of how many zeros are generated. I thought I had it with my if statement but it does not increment correctly. counter2 will increment sometimes when rand()%2 == 0 and other times not. Then it will also increment when rand()%2 == 1 or 2. Please help. Thanks

1
2
3
4
if (rand() % 2 == 0)
		{
			counter2++;
		}



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
  #include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{

	srand(time(0));
	
	int counter2 = 0;

	for (int counter = 1; counter <= 120; counter++)
	{
                int x;
		cout << setw(4) << (x=rand() % 3) << "/";

		

		if (counter % 15== 0)
			cout << endl << endl;
		
		if (x == 0)
		{
			counter2++;
		}
                cout << counter2;

	
        }
	
	cout << "There were " << counter2 << " zeros counted" << endl;

	
        system("pause");

	return 0;
}
Last edited on Nov 16, 2014 at 10:48pm
Nov 16, 2014 at 9:01pm
1) rand() % 2 can generate onlt 0 or 1
2) Line 17: you are generating random number and outputting it on the screen.
Line 24: you are generating another different random number and testing it for 0;
Nov 16, 2014 at 10:27pm
Any way someone could hint at how to reference the same pool of random numbers when calling rand() twice in same program? I am a struggling to figure it out. Thanks for the reply MiiNiPaa.
Nov 16, 2014 at 10:32pm
I'd save the rand() value to a variable in the loop that can be printed out and counted if 0.
Nov 16, 2014 at 10:49pm
Thank you. Seems so obvious after the fact but obviously not for me.
Topic archived. No new replies allowed.