Modulo runs incorrectly

Hi there,

I seem to be having an issue with modulo (%).

When I run the following code it always hits the else regardless of whether y%2 == 1

       if (y % 2 == 1)//ISSUE: Runs the else regardless??....
		{
			position.X = -1220 + (y * 110 / 2); //Move in full blocks
		}
		else
		{
			position.X = -1220 + (y + 1 * 110 / 2); //Move in half blocks
		}

Any ideas?

The modulo works perfectly. Try putting in log messages to test it. For example:

	int32 y;
	for (y = 0; y < 100; y++)
	{
		UE_LOG(YourLog, Warning, TEXT("y: %d"), y);
		
		if (y % 2 == 1)
		{
			UE_LOG(YourLog, Warning, TEXT("y % 2 == 1"));
		}
		else
		{
			UE_LOG(YourLog, Warning, TEXT("y % 2 != 1"));
		}

	}

The problem is not the modulo, it’s the equation in your if and else statements… they equate to being exactly the same because of order of operations. You need to enforce your operations order with parentheses.

What you have:

if: y * 110 / 2

else: y + 1 * 110 / 2

What it does:

if: (y * (110 / 2))

else: (y + (1 * (110 / 2)))

So if Y were, say, 5:

if: (5 * (110 / 2)) = 275

else: (5 + (1 * (110 / 2))) = 275

I dont think this is right.

Running through it now 3 % 2

comes back as:
if: -1000
else: -1055

So they don’t equal the same

Hi Nickyc,

I suppose that your Y is negative and in this case, operator % returns -1 or 0. Try to use abs.

Hope it helps!

I was wrong. At least, when I said that they will equate to the same, and when I said that:

(5 + (1 * (110 / 2))) = 275

I was wrong, because that equals 60.

But unfortunately you are also incorrect, I believe. Upon closer inspection:

In the if, you are multiplying Y to (110 / 2).

In the else, you are adding the Y to (110 / 2).

The +1 is meaningless because it will always be multiplied by the result of (110/2) first.

And, when you say you’re running 3%2 and it comes back -1000 in the if and -1055 in the else, that’s impossible unless you ran the code differently than how you posted it here.

If Y = 3, then

-1220 + (y * 110 / 2) = -1055

and

-1220 + (y + 1 * 110 / 2) = -1162

You can test that with the following code:

int32 y;
	for (y = 0; y < 100; y++)
	{
		float test1 = -1220 + (y * 110 / 2);
		float test2 = -1220 + (y + 1 * 110 / 2);

		UE_LOG(YourLog, Warning, TEXT("y: %d ... test1: %f ... test2: %f"), y, test1, test2);

		if (y % 2 == 1)
		{
			test1 = -1220 + (y * 110 / 2);
			UE_LOG(YourLog, Warning, TEXT("y % 2 == 1... result: %f"), test1);
		}
		else
		{
			test2 = -1220 + (y + 1 * 110 / 2);
			UE_LOG(YourLog, Warning, TEXT("y % 2 != 1... result: %f"), test2);
		}
	}