I'm getting hosed by some calculations that are coming out wrong because the values are ints instead of floats.

Let's say we've got

Code:

var int X, Y;
X = 100;
Y = 90;

...and I've got a check system set up

Code:

if ( X/Y < 1)
`log("A");
else if ( X/Y > 1 )
`log("B");
else if ( X/Y == 1)
`log("C");

Now for this example I could just check if (X > Y) but this is just an example. This keeps popping up for me as a problem in all sorts of places.

If I run that code above, my result is going to be "C" because X/Y will NOT calculate out to 1.11111 but instead to 1.

I thought I could typecast the calculation by doing

Code:

if (float(X/Y) < 1)

but that calculates out to be 1.00000 because X/Y still calculates to an int value, which I just change into a float.

I tried

Code:

if (float(X)/float(Y) < 1 )

but that gives me a compile error saying there's a type mismatch.

There are a couple things I am interested in knowing.

1) Where and when are values changed between types? Like, if I have a line of code that starts with declaring "intVar = " how will that effect how things are calculated as ints vs floats? What about "intVar += "? I need to understand when values are changed between types so I know when to expect a problem. There have been times when I have anticipated a problem and didn't get one, and vice-versa.

2) What is the proper way to calculate int values to float results? Like say I'm feeding a variable the result of a long-A calculation, and all the variables inside are ints, but I want the calculations done as floats so that I don't lose precision halfway through? Like if I have

Code:

Local int X, Y, Z;
Y = 1024;
Z = 1463;
X = Y * (2048 / Z);

I would get X = 1024 when I'm expecting to get X = 1433.

I could copy these out into float duplicates like

Code:

Local int X, Y, Z;
Local float fX, fY, fZ;
Y = 1024;
Z = 1463;
fY = Y;
fZ = Z;
fX = fY * (2048 / fZ);
X = fX;

which is what I have been doing, but this takes up more time and memory, both for programmer and computer. I'm sure there's a smarter way using typecasting, but I don't know all the rules for that, nor for the equations as they stand, to know how to use that efficiently.

## Bookmarks