- Home /
Simple math always returns 0
Hello all, I'm trying to do some simple math in a script and then output those numbers. However, the value that is output is always 0 for some reason.
I've triple checked the math and there seems to be no problem with it so I am stumped. Below is the code.
float carMaxRPM = 8000f;
int numberOfPoints = 20;
List<float> listOfPoints;
void CalcPoints(){
for (int i = 0; numberOfPoints > i; i++)
{
//RPM point is generated based on amount of points for the graph.
var rpmPoint = carMaxRPM * (i / numberOfPoints);
listOfPoints.Add(rpmPoint);
}
}
Any help? I've also tried using Mathf.Lerp(0, carMaxRPM, i/numberOfPoints); but it still returns 0, so I feel I'm doing something very wrong.
Answer by A5B · Jan 21, 2019 at 01:11 AM
The problem is that your code is performing an integer division, rather than floating point division (see here for details). As a result, when you're dividing (i / numberOfPoints), it's going to round down to 0, which is why you're getting zero. You can force it to perform floating point division by adding "(float)" in front of your division:
var rpmPoint = carMaxRPM * ((float)i / numberOfPoints);
Oh! This was it. I feel very dumb for missing this.. you learn something new everyday. Thank you for the help.
An even smoother way would be to just remove the paranthesis in the calculation. Since car$$anonymous$$axRP$$anonymous$$ is a float the calculation should then also be executed as a float.
$$anonymous$$y math is much different, but this just solved such a huge problem for me. I had no idea this was a thing.
THAN$$anonymous$$ YOU so damn much.