if problem

Started by
16 comments, last by scott8 12 months ago

I am trying to get the movey++ variable to increment when move_x is ≤-24. I am trying to get a tank to move up a mountain. let me know if you need more code.

		if (move_x <= -11 && move_y >= 11)
		{
			turn_tank = 1;
			move_y = 11;
			move_x--;
		}
		if (move_x <= -24)
		{
			move_y++;
			turn_tank = 0;
			move_x = -24;
		}
		cout << move_x << " " << move_y << endl;
		move_x--;
		move_y++;
		break;
  
Advertisement

pbivens67 said:
let me know if you need more code.

What we need is a proper question, and information such as “this is what happens when the code runs.” Does the tank just spin its treads at the bottom of the mountain? Does it flip over on its back? Does the program crash? What else have you tried besides code-once-and-run-once?

-- Tom Sloper -- sloperama.com

well first my tank moves up the mountain at an oblique angle then it move on a flat space then it moves west then it tries to move up at an oblique angle again but it does not move up.

@pbivens67 Your two if statements aren't mutually exlusive; if move_x is less than -24, it's also less than -11. So the code in both if statements may be executed (depending on the value of move_y). Is this what you intended?

scott8's answer is probably the explanation you are looking for. In figuring out these kinds of bugs, it's helpful to use a debugger or to add some print statements to see what the variable values are when you observe the undesired behavior.

I want the move_y++ to increment exclusive of the above if stastement

pbivens67 said:

I want the move_y++ to increment exclusive of the above if stastement

But you see how the code you wrote doesn't say that, right?

You may want to do something like putting the `if (move_x <= -24)` block first, and then use `else if …`, so the other block won't be executed if the first one was executed.

In any case, once you have written the code, you can think of some values for the variables and run through the code as if you were the computer, then check if that does what you want it to do. There are more formal ways to do that, like writing unit tests which specify the desired results, but those are probably overkill at this stage in your learning how to program.

well I have adjusted my code, so it moves up the first hill and then it moves on the plane but it does not move up the second hill it just moves straight. here is my updated code.

		if (move_y <= -24)
		{
			move_y++;
			turn_tank = 0;
			move_x = -24;
		}
		else if (move_x <= -11 && move_y >= 11)
		{
			turn_tank = 1;
			move_y = 11;
			move_x--;
		}
		cout << move_x << " " << move_y << endl;
		move_x--;
		move_y++;
		break;

Can you try to add some code to print the values of the variables at different stages, to help you understand what's going on when you see the behavior you don't like?

This topic is closed to new replies.

Advertisement