Home > Enterprise >  How do I avoid getting -0 when dividing in c
How do I avoid getting -0 when dividing in c

Time:08-27

I have a script in which I want to find the chunk my player is in. Simplified version:

float x = -5
float y = -15
int chunkSize = 16

int player_chunk_x = int(x / chunkSize)
int player_chunk_y = int(y / chunkSize)

This gives the chunk the player is in, but when x or y is negative but not less than the chunkSize (-16), player_chunk_x or player_chunk_y is still 0 or '-0' when I need -1

Of course I can just do this:

if (x < 0) x--
if (y < 0) y--

But I was wondering if there is a better solution to my problem.

Thanks in advance.

CodePudding user response:

Since C 20 it's impossible to get an integral type signed negative zero, and was only possible in a rare (but by no means extinct) situation where your platform had 1's complement int. It's still possible in C (although rare), and adding 0 to the result will remove it.

It's possible though to have a floating point signed negative zero. For that, adding 0.0 will remove it.

Note that for an integral -0, subtracting 1 will yield -1.

CodePudding user response:

Your issue is that you are casting a floating point value to an integer value.

This rounds to zero by default.

If you want consistent round down, you first have to floor your value:

int player_chunk_x = int(std::floor(x / chunkSize);

CodePudding user response:

If you don't like negative numbers then don't use them:

int player_chunk_x = (x - min_x) / chunkSize;
int player_chunk_y = (y - min_y) / chunkSize;

CodePudding user response:

If you want integer, in this case -1 on ( -5 or anything like it ) then this is possible using a math function:

Possible Ways :

  1. using floor ->
float x = -5;
float y = -15;
int chunkSize = 16;

int player_chunk_x = floor(x / chunkSize) 
// will give -1 for (-5 % 16);
// 0 for (5) 
// 1 for any value between 1 & 2 and so on 

int player_chunk_y = floor(y / chunkSize);
  • Related