0

I'm currently working on a Trafficsimulation which is based on a grid system. For some reason the line of code, which calculates how many tiles i have to add always returns 0. I have tried it without the variables but it still doesn't work.

double blocksToAdd = o.getVelocity()*((1000/Main.FPS)/1000);

Currently the velocity is equal to 1.0f and the Simulation runs at 10 FPS, so blocksToAdd should be 0.1, but it always returns 0.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Lca311
  • 71
  • 7

2 Answers2

1

Most likely due to integer division tuncating the fraction.

Replace the first 1000 with 1000.0 and all will be well. (The latter is a floating point double literal which causes the division to be computed in floating point.) There are other remedies but I find this one to be the clearest.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

Since Main.FPS is an int, 1000/Main.FPS is also an int, equal to 100. You then proceed to calculate 100/1000. Since this is an integer division, only the "whole" part is taken, giving 0.

Using floating point literals will cause Java to use floating point division, which should produce the correct result:

double blocksToAdd = o.getVelocity() * ((1000.0 /Main.FPS ) / 1000.0);
// Here --------------------------------------^--------------------^
Mureinik
  • 297,002
  • 52
  • 306
  • 350