Battle !!!

Hi! Here is my code of Tank Battle
when you press 1 the first tank should attack when you press 2 the second tank should attack
but when I press 1 and the first tank attacks after pressing 2 the second tank does nothing
can't find the error, help please
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
	t1.h = t1.h0;
	t2.h = t2.h0;
	do
	{
		std::cout << "Enter the number of the attacking tank <1 or 2> \n";
		int tank_num;
		std::cin >> tank_num;
		if(tank_num == 1)
		{
			t2.h -= (t1.A*(1-t2.d))*(t1.h/t1.h0);
			if(t2.h <= 0)
			{
				std::cout <<"Tank2 is dead\n";
				break;
			}
			else
				std::cout << "Tank1 health: " << t1.h << "\nTank2 health: " << t2.h << "\n";
		}
		if(tank_num == 2)
		{
			t1.h -= (t2.A*(1-t1.d))*(t2.h/t2.h0);
			if(t1.h <= 0)
			{
				std::cout << "Tank1 is dead\n";
				break;
			}
			else
				std::cout  << "Tank1 health: " <<  t1.h << "\nTank2 health: " << t2.h << "\n";
		}
	}while(t1.h > 0 && t2.h > 0);
Last edited on
Hello kizhvac kampazitr,

I came to the conclusion that lines 45 and 56 were the problem. Then I figured out that the formulas ended up with an answer that has a decimal value that you stored in an "int" variable. This will drop the decimal part which could leave a value of 0.

For a test, in the struct, I changed the "int"s to "double"s and it worked better.

See what you think,

Hope that helps,

Andy
yes with doubles it works better but the tasks condition is
Health of the tank is represented by an integer.
Hello kizhvac kampazitr,

If the health of the tank needs to be an "int" then try this:
t1.h -= (t2.A*(1 - t1.d))*(static_cast<double>(t2.h) / static_cast<double>(t2.h0));.

Without t?.h and t?.h0 not being a double this would be integer division which drops the decimal portion and could most of the time be zero leaving the whole formula as zero. The "static_cast" will solve the problem leaving a positive number to subtract from t1 or t2.

Hope that helps,

Andy
Yes, already tried that. Works as it should
Thanks :D
Topic archived. No new replies allowed.