Cannot increment with greater than condition

I have two different random values, and each time the loop iterates a value will be greater than another and increment incr1 or incr2 . My problem though is that it increments to 1 then goes back to zero and repeats the process .
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
	srand(static_cast <unsigned int> (time(0)));
	int x = 0;
	while (x != 50)
	{
		x++;
                int rand1 = rand() % 100;
		int rand2 = rand() % 100;
		int incr1 = 0;
		int incr2 = 0;


		if (rand1 > rand2)
		{
			incr1++;
		}
		else
		{
			incr2++;
		}
	        std::cout << "increase1 " << increase1 << std::endl;
		std::cout << "increase2 " << increase2 << std::endl;
	}

I tried to see if each time one of the values reached one it would increment another value, but that does not work in this case. How may I fix this so that it will count the number of times a value is greater than another as seen on line 12?
Last edited on
lines 21 and 22 seem incorrect for anything I can make sense of. Perhaps those should be up at line 11 or so?

it is USUALLY a bad idea to make variables INSIDE a loop at all. There are some special circumstances where it can help things, but most of the time, it causes problems. I would move ALL the variables OUT of the loop and then update their values IN the loop instead. Its not necessary, but it will help you I think.

consider using <random> instead of C's random numbers. The sooner you get in this habit, the better off you will be.
Last edited on
Yeah probably , the declaration there didn't seem unnatural to me . But yes declaring them in the loop was my problem , thanks.
Last edited on
Whether a variable is defined inside or outside of a loop depends upon what scope is required. If a variable is required only within the loop and are initialised every time through the loop (eg rand1, rand2) then these are defined within the loop. If the value is required outside of the loop (eg incr1, incr2), then these need to be defined before the loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <ctime>
#include <cstdlib>

int main() {
	std::srand(static_cast <unsigned int> (time(nullptr)));

	size_t  incr1 {};
	size_t  incr2 {};

	for (size_t x = 0; x < 50; ++x) {
		const auto rand1 {rand() % 100};
		const auto rand2 {rand() % 100};

		if (rand1 > rand2)
			++incr1;
		else
			++incr2;
	}

	std::cout << "increase1 " << incr1 << '\n';
	std::cout << "increase2 " << incr2 << '\n';
}

Topic archived. No new replies allowed.